【问题标题】:Rails - rescue_from exception handling a exception type differently based on what method the exception is raised fromRails - rescue_from 异常根据引发异常的方法不同地处理异常类型
【发布时间】:2015-05-28 15:36:51
【问题描述】:

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. (有点离题,但是)通常以不同的方法以不同的方式处理相同类型的错误是一种不好的做法吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 exception-handling


    【解决方案1】:

    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
    

    【讨论】:

    • 我在 Rails 4 的 ruby​​doc 中找不到这个方法,这仅在 Rails 2.3 中可用吗?
    • 看起来不像 ruby​​doc 中记录的;它绝对可以在 rails 4 中使用;它是控制器助手的一部分。 github.com/rails/rails/blob/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多