How to raise a custom error code in sinatra?

le_me picture le_me · Nov 27, 2012 · Viewed 21.1k times · Source

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

Answer

Sean Redmond picture Sean Redmond · Nov 29, 2012

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