【问题标题】:rescue_from StandardError overridding other rescue_from blocks覆盖其他rescue_from块的rescue_from标准错误
【发布时间】:2020-05-12 23:21:26
【问题描述】:

我正在尝试创建一个模块来处理我在include 在我的application_controller.rb 中的 API 错误。这是我模块的self.included 函数。

def self.included(clazz)
  clazz.class_eval do

    rescue_from ActiveRecord::RecordNotFound do |e|
      respond(:record_not_found, 404, e.message)
    end
    rescue_from ActiveRecord::RecordInvalid do |e|
      respond(:record_invalid, 422, e.record.errors.full_messages)
    end
    rescue_from ActionController::ParameterMissing do |e|
      respond(:bad_request, 400, e.message)
    end
    rescue_from StandardError do |e|
      respond(:standard_error, 500, e.message)
    end
  end
end

我遇到的问题是StandardError 捕获所有错误,包括我在其他rescue_from 块中定义的其他错误。

我想实现这样的目标:

begin

rescue ActiveRecord::RecordNotFound => e

rescue ActiveRecord::RecordInvalid => e

rescue ActionController::ParameterMissing => e

rescue StandardError => e

end

提前感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-6


    【解决方案1】:

    我会将其重构为单个 rescue_from,然后通过检查 e.class 进行深入分析:

    rescue_from StandardError do |e|
      case e.class
      when ActiveRecord::RecordNotFound
        respond(:record_not_found, 404, e.message)
      when ActiveRecord::RecordInvalid
        respond(:record_invalid, 422, e.record.errors.full_messages)
      when ActionController::ParameterMissing
        respond(:record_not_found, 400, e.message)
      else
        respond(:standard_error, 500, e.message)
      end
    end
    

    【讨论】:

      【解决方案2】:

      问题是rescue_from 处理程序是

      处理程序是继承的。从右到左,从下到上,向上搜索它们。

      这意味着块以相反的顺序执行,因此您的 4 个rescue_froms 看起来更像:

      begin
      rescue StandardError => e
      rescue ActionController::ParameterMissing => e
      rescue ActiveRecord::RecordInvalid => e
      rescue ActiveRecord::RecordNotFound => e
      end
      

      相反。最后添加的处理程序是第一个执行的处理程序这一事实允许诸如子控制器之类的事情覆盖父控制器中的处理程序。因此,要解决此问题,只需颠倒您定义 rescue_from 块的顺序,事情就会按您的预期工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-12
        • 2016-08-29
        • 2012-01-24
        • 1970-01-01
        • 2016-05-11
        • 2017-12-23
        • 2017-09-22
        • 1970-01-01
        相关资源
        最近更新 更多