如何在 Sinatra 中定义 JSON 的全局错误处理程序

发布于 2024-12-25 14:38:38 字数 260 浏览 3 评论 0原文

我想定义一个错误块(或其他东西),它将返回所有以JSON格式格式化的异常加上返回标准http代码(例如404表示未找到,303表示身份验证错误等)。

比如:

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

谢谢!

I would like to define an error block (or something) that would return all exceptions formatted in JSON somehow plus returning the standard http code (e.g. 404 for not found, 303 for auth errors etc).

Something like:

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

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸵鸟症 2025-01-01 14:38:38

这应该有效:

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

This should work:

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

Test it with curl to see that it works.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文