Rails - rescue_from 根据引发异常的方法以不同方式处理异常类型

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

Rails的:rescue_from接受一个特定的异常类型和一个方法作为参数如下:

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

但这意味着它将在整个控制器中以相同的方式处理指定的异常。

如果我想根据引发异常的方法以不同方式处理异常类型怎么办,示例:

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

我有以下问题:

  1. 这也可以通过使用 :rescue_from 来完成吗(可以传入任何类型的选项)?

  2. 如果没有,有没有更好的办法处理这种情况?

  3. (有点跑题但是)一般来说,在不同的方法中以不同的方式处理相同类型的错误是不是一种不好的做法?

Rails 通过 controller_nameaction_name 方法提供对 controller and action names 的访问。您可以使用它根据引发异常的方法以不同方式处理异常。

示例:

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

  protected

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