Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise a custom error code in sinatra?

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 
like image 407
le_me Avatar asked Nov 27 '12 17:11

le_me


2 Answers

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 
like image 154
Sean Redmond Avatar answered Sep 24 '22 23:09

Sean Redmond


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

like image 42
germanlinux Avatar answered Sep 26 '22 23:09

germanlinux