【问题标题】:Global error handling and the order of included rescue_from全局错误处理和包含的rescue_from的顺序
【发布时间】:2020-02-26 06:27:15
【问题描述】:

为了让我的程序按预期工作,rescue_from 的顺序并不直观。我想知道为什么会这样或者我哪里出错了?

我正在尝试这个错误处理解决方案。

https://medium.com/rails-ember-beyond/error-handling-in-rails-the-modular-way-9afcddd2fe1b#.yvuf06281

我的错误处理程序与github repo中的相同

module Error
  module ErrorHandler
    def self.included(clazz)
      clazz.class_eval do
        rescue_from ActiveRecord::RecordNotFound do |e|
          respond(:record_not_found, 404, e.to_s)
        end
        rescue_from CustomError do |e|
          respond(e.error, e.status, e.message.to_s)
        end
        rescue_from StandardError do |e|
          respond(:standard_error, 500, e.to_s)
        end
      end
    end

这导致我的错误总是被捕获在StandardError 块中,跳过ActiveRecord::RecordNotFoundCustom 错误块。

但是,如果我切换顺序(StandardError 在执行中更高),它会正确捕获其他类型的错误。

    def self.included(clazz) #includes module as a class method
      clazz.class_eval do
        rescue_from StandardError do |e|
          respond(:standard_error, 500, e.to_s) 
        end

        rescue_from ActiveRecord::RecordNotFound do |e|
          respond(:record_not_found, 404, e.to_s)
        end

        rescue_from CustomError do |e|
          respond(e.error, e.status, e.message.to_s)
        end
      end
    end

为什么在顶部设置 StandardError 会起作用?

【问题讨论】:

    标签: ruby-on-rails ruby exception error-handling module


    【解决方案1】:

    last declared handler has the highest priority,因此您应该首先声明通用处理程序(例如,一个用于StandardError)然后是特定处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-17
      • 2013-03-06
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 2015-08-04
      相关资源
      最近更新 更多