404 and other Errors in Sinatra

One of the nice things when you start using Sinatra are the cool error pages. sinatra doesnt know this ditty

Most web apps need to cater for errors and it is really easy to do in Sinatra.

404 Errors

These occur when the page or resource cannot be found. You deal with this using the following code block:

not_found do
  "Your page cannot be found"
end

This will display the message “Your page cannot be found”. You can use a more in-depth message page in your views instead and this will incorporate the site layout in your layout.erb file.

not_found do
  erb :'404'
end

This can even be written as a one-liner:

not_found { haml :'404' }

Notice that if you call the file 404.erb, then you will have to put it in quotes, as symbols cannot start with a number.

500 Errors

These occur when there is an internal server error - usually something has gone wrong with your app. This code will serve up a page

error do
  @error = request.env['sinatra_error'].name
  haml :'500'
end

This will then give you access to an instance variable called @error in your view. Useful methods for this are @error.name and @error.message.

You can also create custom errors using the following notation:

error BigError do
   "BOOM! There's been a big mistake! " + request.env['sinatra.error'].message
end

You can then raise this error, with a suitable message like so:

get '/' do
  raise BigError, 'Are you sure you closed all your         brackets?'
end

This will produce the following error message:

BOOM! There's been a big mistake! Are you sure you closed all your brackets?

It’s useful to set up error handling for each project early on. I usually stick these two lines at the beginning of a project file:

not_found { haml :'404' }
error { @error = request.env['sinatra_error'] ; haml :'500' }

Does anybody else have any more advice or tips about error handling in Sinatra? If so, leave a comment!

blog comments powered by Disqus