ruby 如何在 sinatra 中引发自定义错误代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13589450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to raise a custom error code in sinatra?
提问by le_me
I did the following in my sinatra app:
我在我的 sinatra 应用程序中执行了以下操作:
disable :show_exceptions
disable :raise_errors
error do
haml :error, :locals => {:error_message => request.env['sinatra.error'].to_s}
end
get '/error' do
raise "ERROR!!"
end
If I visit /errorI get a 500 - Internal Server Errorresponse code, which is god and wanted. But how do I change the code to, eg, 404 or 501?
如果我访问,/error我会得到一个500 - Internal Server Error响应代码,这是上帝想要的。但是如何将代码更改为例如 404 或 501?
The answer:
答案:
disable :show_exceptions
disable :raise_errors
get '/error' do
halt(404,haml(:error, :locals => {:error_message => request.env['sinatra.error'].to_s}))
end
采纳答案by Sean Redmond
Something like raise 404raises an error just like raise ZeroDivisionErrorwould, which causes your app to throw a 500 Internal Server Error. The simplest way to return a specific error is to use status
类似于raise 404会引发错误raise ZeroDivisionError,这会导致您的应用引发 500 内部服务器错误。返回特定错误的最简单方法是使用status
get '/raise404' do
status 404
end
You can also add a custom response body with body
您还可以添加自定义响应正文 body
get '/raise403' do
status 403
body 'This is a 403 error'
end
回答by germanlinux
I use this in block
我在块中使用它
if 'condition' then do something else halt 500 , "error message" end #only without error erb :my_template
In case of error my log is like this
HTTP/1.1" 500 13 0.1000
如果出现错误,我的日志就像这样
HTTP/1.1" 500 13 0.1000
回答by jboursiquot
Instead of raise "ERROR!!", try just doing error 404or error 501with optional status message after the status code.
而不是raise "ERROR!!",尝试在状态代码之后执行error 404或error 501使用可选的状态消息。
Update:
If you define your error handler as
error 400..501 do...for example, you can use error 501 "ERROR!!"in your "/error"route. This will also put your "ERROR!!" message in env['sinatra.error'].message.
更新:error 400..501 do...例如,如果您定义错误处理程序
,则可以error 501 "ERROR!!"在您的"/error"路线中使用。这也会把你的“错误!!” 留言 env['sinatra.error'].message。

