ruby-on-rails - 全局错误处理和包含的rescue_from的顺序

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

为了让我的程序按预期工作,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 block 中,跳过 ActiveRecord::RecordNotFoundCustom 错误 block 。

但是,如果我切换顺序(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 放在顶部会起作用?

最佳答案

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

关于ruby-on-rails - 全局错误处理和包含的rescue_from的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634123/

相关文章:

c++ - 使用不支持异常的 C++ 编译器?

ruby-on-rails - Ruby on Rails 应用程序中搜索结果页面上的 Sphinx 连接错误

ruby - 将注入(inject)与哈希数组一起使用

ruby-on-rails - 在 Ruby on Rails 应用程序中随处调用方法

ruby - 有效地将内存中的文件内容通过管道传输到命令行命令

ruby-on-rails - 从 Ruby on Rails 执行系统任务的最佳方式是什么?

java - Class.forName() 和 ClassNotFoundException

c# - dll 中的异常处理

ruby-on-rails - 架构arm64构建nokogiri-xmlsec-instruct的 undefined symbol Ruby gem

css - 如何限制 Bootstrap 容器的高度