【问题标题】:How to define global error handler for JSON in Sinatra如何在 Sinatra 中为 JSON 定义全局错误处理程序
【发布时间】:2012-01-08 13:22:56
【问题描述】:

我想定义一个错误块(或其他东西),它将以某种方式返回 all 格式为 JSON 的异常 plus 返回标准 http 代码(例如 404 表示未找到, 303 用于身份验证错误等)。

类似:

error do
  e = env['sinatra.error']
  json :result => 'error', :message => e.message
end

谢谢!

【问题讨论】:

  • 您希望将 http 状态代码包含在您的 JSON 对象中,还是只是在寻找要附加到 HTTP 响应的状态代码?

标签: ruby sinatra


【解决方案1】:

这应该可行:

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 测试它是否有效。

【讨论】:

  • 您可以使用“set :show_exceptions, false”禁用error_handler,而不是重新定义环境
猜你喜欢
  • 2019-03-07
  • 1970-01-01
  • 2013-03-06
  • 2018-04-27
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2013-07-01
  • 1970-01-01
相关资源
最近更新 更多