在 sinatra 中调用暂停不会设置 sinatra.error
我的用例是我想在 sinatra 中进行错误处理。为此,我按如下方式设置错误处理程序
error 0..600 do
@@logger.error("error reason #{env['sinatra.error']}")
end
如果错误是由显式引发异常引起的,则 sinatra.error 变量会设置得很好,
get '/' do
raise "Fail the request"
end
但如果使用暂停来终止请求,则不会设置 sinatra.error 。查看 sinatra 代码,这似乎符合预期,因为抛出 :halt 会导致控制流一直向上调用,从而绕过 sinatra.error 变量的设置。
我的问题是如何将错误处理程序与停止一起使用,以便我可以在错误处理程序中找到错误的原因。
My use case is that I would like to do error handling in sinatra. For this I am setting up the error handler as follows
error 0..600 do
@@logger.error("error reason #{env['sinatra.error']}")
end
The sinatra.error variable gets set fine if the error was caused by explicitly raising an exception
get '/' do
raise "Fail the request"
end
But if halt is used to terminate the request then sinatra.error does not get set. Looking into sinatra code this appears to be as expected because throwing :halt causes the control flow to go all the way up to invoke and thus bypassing the setting of sinatra.error variable.
My question is how to use the error handler along with the halt so that I can get the cause of the error in the error handler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您所看到的行为源于
halt
的预期目的。当您调用它时,您不一定发出错误信号;而是发出错误信号。您只想立即停止执行,这在过滤器中特别有用。如果您检查 Sinatra 的 README,它会说您使用halt
来“立即停止过滤器或路由使用中的请求”。当然,您通常会因为错误而这样做。值得注意的是,您定义的错误处理程序不仅在发生错误时被调用,而且在提供常规请求(包括状态为 200 的请求)时也会被调用。在这些情况下,
env[sinatra.error] 也不会被设置。
您可以在错误处理程序中执行的操作是检查异常,如果不可用,则检查响应代码。例如(请注意,这是一个经典应用程序):
一个结果是,在此处理程序中,正常请求与被
halt
中断的请求无法区分,因为两者都会生成 200 状态代码。但是,如果您使用halt
来报告错误,那么无论如何您都应该使用 500 这样的错误代码。I think the behavior you're seeing stems from the intended purpose of
halt
. When you call it, you aren't necessarily signaling in error; you just want execution to stop immediately, which can be particularly useful in a filter. If you check Sinatra's README, it says that you usehalt
to "immediately stop a request within a filter or route use". Granted, you will usually do it because of an error.It is also interesting to notice that the error handler you defined gets called not only when errors occur, but also when regular requests are served, including ones with status 200. And in those cases,
env[sinatra.error]
won't be set either.What you can do in your error handler is to check for an exception and, if it's not available, check the response code. For example (note that this is a classical application):
One consequence is that, in this handler, normal requests are indistinguishable from those interrupted by
halt
, because both generate a 200 status code. However, if you are usinghalt
to report errors, then you should be using an error code like 500 anyway.