Search code examples
rubyerror-handlingsinatra

Global rescue and logging exceptions in Sinatra


How do I specify a global rescue in case of an exception, and if you use Sinatra for an API or application, how do you handle logging?


Solution

  • 404s can be handled with the help of the not_found method like eg:

    not_found do
      'Site does not exist.'
    end
    

    500s can be handled by calling the error method with a block, eg:

    error do
      "Application error. Pls try later."
    end
    

    The details of the error can be accessed via the sinatra.error in request.env like so:

    error do
      'An error occured: ' + request.env['sinatra.error'].message
    end