I have two rescue_from handlers, a 404 handler, and a catch all handler. The catch all always gets called for ActiveRecord::RecordNotFound exceptions and the 404 handler never gets called. My expectation is that the handler with more specificity will be called but this does not happen.
application_controller.rb
# ActiveRecord 404
rescue_from ActiveRecord::RecordNotFound do |e|
...
end
# Catch all unhandled exceptions
rescue_from Exception do |e|
...
end
The api docs for rescue_from says the following:
Handlers are inherited. They are searched from right to left, from bottom to top, and up the hierarchy. The handler of the first class for which exception.is_a?(klass) holds true is the one invoked, if any.
Am I interpreting the about statement wrong. How do I get behavior I'm looking for?
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.
The 404 handler never gets called because the catch all always gets called first in your example. The problem is in the ordering of the handler definitions. They are evaluated from bottom to top meaning that your last defined handler will have the highest priority and your first defined handler will have the lowest priority. If you switch the order then you will get the behavior you want.
# Catch all unhandled exceptions
rescue_from StandardError do |e|
...
end
# ActiveRecord 404
rescue_from ActiveRecord::RecordNotFound do |e|
...
end
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