Manejo de Errores

  1. The HTTP specification states that response status in the range 200-299 indicate success in processing a request
  2. 500-599 is reserved for server errors
  3. Sinatra offers helpers for the 404 (Not Found) and 500 (Internal Server Error) status

not_found

When a Sinatra::NotFound exception is raised, or the response’s status code is 404, the not_found handler is invoked:

not_found do
  'This is nowhere to be found.'
end

error

The error handler is invoked any time an exception is raised from a route block or a filter.

The exception object can be obtained from the sinatra.error Rack variable:

error do
  'Sorry there was a nasty error - ' + env['sinatra.error'].name
end
Custom errors:

error MyCustomError do
  'So what happened was...' + env['sinatra.error'].message
end
Then, if this happens:

get '/' do
  raise MyCustomError, 'something bad'
end
You get this:

So what happened was... something bad
Alternatively, you can install an error handler for a status code:

error 403 do
  'Access forbidden'
end

get '/secret' do
  403
end
Or a range:

error 400..510 do
  'Boom'
end
Sinatra installs special not_found and error handlers when running under the development environment to display nice stack traces and additional debugging information in your browser (esto es, en producción estos handlers son mucho mas "parcos").



Subsecciones
Casiano Rodriguez León 2015-01-07