抢救多个异常类型,继承 - 匹配的顺序是什么?

时间:2018-01-18 16:09:58

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

我的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

1 个答案:

答案 0 :(得分:2)

查看它所声明的docs

  

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

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

  

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

     

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

相关问题