Sinatra provides a helpful pair of special handlers for 404 and 500 errors. By default, Sinatra has an ugly “Not Found” and “Error” message, these allow you to customize them, and render your own pages.
It’s pretty simple:
# Render views/404.haml not_found do haml :'404' end # Render views/500.haml # @e holds whatever was thrown, in this example, a string, # but it could have an Error class of some sort. error do @e = request.env['sinatra_error'] haml :'500' end get '/' do raise "Error happened!" end
Notice that I had to surround the templates in single quotes. This is because ruby syntax doesn’t let symbol’s first character be a number. By quoting it, it gets around that issue.