Is there a way to catch any type of error the Ruby/Rails encounters?
I am making a network request. What I have seen so far is, it can return 404, timeout or even any empty response object?
I have handled them individually, it is not DRY, but is there a way to handle all these and those which I have not seen yet gracefully?
Many times even when the response object is analysed, sometimes it may not contain what I am looking for. Sure I can handle them individually.
I am curious to know if it is possible to define a use case to work with, everything apart from it, which I have not imagined, is just thrown an exception and does not break my application.
Is generic error handling possible in Ruby?
Yes its absolutely possible, there are a couple of different levels of rescuing exceptions in Ruby, as noted by Daryll you can specify different exceptions that go to the same handler like
begin
# potentially exception raising code
rescue Exception1, Exception2 => e
# run code if Exception1 or Exception2 get raised
end
You can also catch StandardError, which most Exceptions that you would want to catch inherit from. This is a good option if your looking for a catch all, like try this and keep going no matter what.
begin
# potentially exception raising code
rescue StandardError => e
# run code if StandardError or anything that inherits from StandardError is raised (most errors)
end
You can also catch Exception (Dangerous), which every Exception inherits from (including StandardError). You pretty much never want to do this since things like SyntaxErrors, SignalExceptions (you can catch Control-C and prevent terminating your script with it) and other internal errors also inherit from Exception. See http://blog.honeybadger.io/ruby-exception-vs-standarderror-whats-the-difference/ for some more details
begin
syntax exception
rescue => e
puts "I even catch syntax errors!!!"
end
puts "I'll keep on executing though"
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