Reputation: 3419
I did the following in my sinatra app:
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 /error
I get a 500 - Internal Server Error
response code, which is god and wanted. But how do I change the code to, eg, 404 or 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
Upvotes: 27
Views: 24547
Reputation: 2511
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
Upvotes: 6
Reputation: 4114
Something like raise 404
raises an error just like raise ZeroDivisionError
would, which causes your app to throw a 500 Internal Server Error. The simplest way to return a specific error is to use status
get '/raise404' do
status 404
end
You can also add a custom response body with body
get '/raise403' do
status 403
body 'This is a 403 error'
end
Upvotes: 26
Reputation: 1271
Instead of raise "ERROR!!"
, try just doing error 404
or error 501
with optional status message after the status code.
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
.
Upvotes: 2