Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 1000
Jane Avatar asked Dec 12 '11 14:12

Jane


People also ask

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

How do you handle exceptions in Ruby?

Ruby also provides a separate class for an exception that is known as an Exception class which contains different types of methods. The code in which an exception is raised, is enclosed between the begin/end block, so you can use a rescue clause to handle this type of exception.

Does Ruby have try catch?

In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).

How do you rescue in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.


2 Answers

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
like image 173
Marek Příhoda Avatar answered Oct 10 '22 06:10

Marek Příhoda


I had trouble getting this working out of the box in my dev environment - to get it to work, I had to set show_exceptions to false in my sinatra config.

class BaseApp < Sinatra::Base

  configure { set :show_exceptions, false }

  error do |err|
    raise "Error: #{err}"
  end

end

This setting, when set to true, enables error pages that show backtrace and environment information when an unhanded exception occurs, but I could only fire custom errors by disabling it.

like image 32
lfender6445 Avatar answered Oct 10 '22 06:10

lfender6445