【问题标题】:Rescuing multiple exception types, inherited - what is the order of matching?抢救多种异常类型,继承——匹配的顺序是什么?
【发布时间】:2018-01-18 16:09:58
【问题描述】:

我的 API 控制器有时会抛出 Pundit::NotAuthorizedError,我想使用错误代码 403 呈现特定的 json 响应。对于一般错误,我想渲染其他内容,状态为500

但是 :render_error 救援总是会捕获 Pundit 错误,因此我得到 500。为什么会发生这种情况,我应该怎么做才能避免它?如果我完全删除rescue_from StandardError...,它工作正常。 (ActionController::ParameterMissing 工作正常,所以我猜它与继承有关,但我会假设它会尝试按照代码中给出的顺序匹配异常类型)。

class Api::V1::BaseController < ActionController::API
  include Pundit

  rescue_from Pundit::NotAuthorizedError, with: :render_not_authorized
  rescue_from ActionController::ParameterMissing, with: :render_bad_request
  rescue_from StandardError, with: :render_error

  def  render_not_authorized
     ....
  end

  def  render_error
    ....
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby inheritance error-handling


    【解决方案1】:

    查看docs 的声明:

    处理程序是继承的。从右到左,从下到上,向上搜索它们。 exception.is_a?(klass) 成立的第一个类的处理程序是被调用的处理程序,如果有的话。

    特别注意第一条评论(“按从最通用到最具体的顺序定义处理程序”),其中指出:

    救援处理程序定义越晚,优先级越高。

    最后声明 Exception catch-all 处理程序会产生阻止任何其他处理程序运行的副作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2017-07-12
      • 1970-01-01
      • 2012-07-23
      相关资源
      最近更新 更多