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?
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.
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.
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).
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With