我想定义一个错误 block (或其他东西),它将以某种方式返回以 JSON 格式化的所有异常加上返回标准的 http 代码(例如 404 表示未找到, 303 用于身份验证错误等)。
类似于:
error do
e = env['sinatra.error']
json :result => 'error', :message => e.message
end
谢谢!
最佳答案
这应该有效:
require 'sinatra'
require 'json'
# This is needed for testing, otherwise the default
# error handler kicks in
set :environment, :production
error do
content_type :json
status 400 # or whatever
e = env['sinatra.error']
{:result => 'error', :message => e.message}.to_json
end
get '/' do
raise 'hell'
end
用 curl 测试它是否有效。
关于ruby - 如何在 Sinatra 中为 JSON 定义全局错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772641/