Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine which exception handler rescue_from will choose in Rails?

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?

like image 746
Tim Santeford Avatar asked Feb 02 '12 19:02

Tim Santeford


People also ask

How to handle exception 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 to handle exception 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.


1 Answers

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
like image 101
Brian Bice Avatar answered Oct 11 '22 12:10

Brian Bice