Edward
Edward

Reputation: 1914

Rails - rescue_from exception handling a exception type differently based on what method the exception is raised from

Rails's :rescue_from takes in a specific exception type and a method as parameter as follow:

class ApplicationController < ActionController::Base
  rescue_from User::NotAuthorized, with: :deny_access # self defined exception
  rescue_from ActiveRecord::RecordInvalid, with: :show_errors

  rescue_from 'MyAppError::Base' do |exception|
    render xml: exception, status: 500
  end

  protected
    def deny_access
      ...
    end

    def show_errors(exception)
      exception.record.new_record? ? ...
    end
end

but this implies that it will deal with the specified exception in the same way ALL ACROSS the controller.

What if I want to handle an exception type differently based on what method the exception is raised from, Example:

class MyController < ActionController::Base

  def method_1
    # Do Something
  rescue MyCustomError => e
    handle_exception_for_method_1(e)
  end

  def method_2
    # Do Something
  rescue MyCustomError => e
    handle_exception_for_method2(e)
  end

protected

  def handle_exception_for_method_1(exception)
    # Do Something
  end

  def handle_exception_for_method_2(exception)
    # Do Something
  end

end

I have the following questions:

  1. Can this be done by using :rescue_from as well (with any sort of options to pass in)?

  2. If not, is there any better solution of dealing with this kind of situations?

  3. (Kind of off topic but) Is it a bad practice to handle the same type of error differently in different methods in general?

Upvotes: 3

Views: 2044

Answers (1)

Prakash Murthy
Prakash Murthy

Reputation: 13067

Rails provides access to the controller and action names through controller_name and action_name methods. You could use this to handle exceptions differently based on the what method the exception was raised.

Example:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordInvalid, with: :show_errors

  protected

    def show_errors
      if action_name == "create"
        ...
      elsif action_name == ...
        ...
    end
end

Upvotes: 3

Related Questions