【问题标题】:How to setup a generic error/exception handler callback in Ruby?如何在 Ruby 中设置通用错误/异常处理程序回调?
【发布时间】:2011-11-02 01:50:10
【问题描述】:

我正在处理这个问题:Rails exception notifier in rake tasks

我的问题:是否有任何函数/插件/gem/whatever 来设置通用错误/异常处理程序回调,就像在 PHP 中使用 set_error_handlerset_exception_handler 一样?

我需要一种方法来注册一个回调函数,用作任何begin .. rescue .. end 块之外的总括。例如:

def my_handler *args
  # exception processing code here
end

some_magic_method my_handler

raise "An Exception" # this will be handled by my_handler

在 PHP 中,这可以通过 set_exception_handler 函数来实现。 Ruby/Rails 中有这样的功能吗?

如果存在这样的功能,我可以用简单的方式解决我之前的问题。

只有 Rails 的解决方案可以满足我的需求。

【问题讨论】:

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


    【解决方案1】:

    如果您想在 HTTP 请求处理周期中执行此操作,您可以在应用程序控制器中使用环绕过滤器:

    class ApplicationController < ActionController::Base
      around_filter do |controller, action|
        action.call
      rescue ExceptionXPTO
         # ... handle the exception ...
      end
    end
    

    【讨论】:

    • 我知道,但是很好的提示。但是,这并不能解决一般问题。
    【解决方案2】:

    我不相信 Ruby 提供了一种方法来做到这一点,无论是使用异常还是使用 throw/catch。一般来说,以这种方式做某事是一种代码味道,需要避免。它使控制流非常难以弄清楚。如果可能的话,我会尝试寻找其他方法来解决问题。

    【讨论】:

    • 我部分同意你的观点,我所要求的在概念上类似于 ActionController 中使用的 rescue_from 类方法,但在程序的顶层部分。在某些情况下,它可能非常有用且干燥。
    • 同意,有时它很有用。这就是为什么它是代码味道,而不是反模式:)
    【解决方案3】:

    我找到了我的问题的部分解决方案,适用于我在问题中提到的简单案例。但是,这无法捕获异常,但如果有人只需要异常记录或报告,它会很有用。

    #!/usr/bin/env ruby
    
    at_exit do
      if $!
        puts "Program ended with an exception #{$!.message}"
        puts $!.backtrace.join("\n")
        # or log the exception here
      end
    end
    
    loop do
      value = rand(3)
      puts "Value is #{value}"
      break if value == 2 
      raise "An Exception" if value == 0
    end
    
    puts "Program ended normally"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2015-03-29
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多