not_found and error handlers for custom 404 and 500 responses
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.
September 10th, 2008 at 2:25 pm
note that #not_found is actually only a shorthand for
error NotFound do
‘err!’
end
September 10th, 2008 at 2:46 pm
We should really make it easier to get at `request.env[‘sinatra.error’]`. Maybe EventContent#error or EventContext#exception or something.