Ruby相当于PHP set_error_handler

问题描述

| 我才刚接触Ruby / ROR,但是需要快速编写一个类来处理错误并对其进行处理。我已经找到了所需的其他重要示例/教程,但是我很难找到PHP的“ set_error_handler \”的最佳替代方案。 我的目标是: 我想写一个可以自动捕获任何红宝石级错误的类。 我希望当有自定义错误/异常要报告时,用户也可以调用该类。 我希望此功能适用于任何ruby应用程序,但我的主要重点也适用于ruby-on-rails应用程序。谢谢你的建议。     

解决方法

我认为Rails中最接近的等效项是rescue_from-它允许您指定代码将捕获任何给定的异常(某些模板错误除外-尽管有一些方法可以解决此问题)。如果需要,可以将其交给其他班级。因此,我想您要做的是: 在app / controllers / application_controller.rb中:
class ApplicationController < ActionController::Base
  rescue_from Exception do |e|
    MyExceptionHandler.handle_exception(e)
  end
end
在lib / my_exception_handler.rb中:
class MyExceptionHandler
  def self.handle_exception exception
    # your code goes here
  end
end
如果有帮助,请让我知道,我将挖掘出如何捕获模板错误的链接。     ,
begin
  #require all_kinds_of_things
  \"abc\".size(1,2)
  123.reverse
  # rest of brilliant app
rescue Exception => e #Custom,catch-all exeption handler
  puts \"Doh...#{e}\"
  print \"Do you want the backtrace? (Y) :\"
  puts e.backtrace if gets.chomp == \"Y\"
end
    ,定义
ApplicationController#rescue_in_public(exception)
,并将您的自定义处理代码放在此处。 这就增强了Rails在顶层的默认异常处理-在生成HTTP响应之前。随着您的Rails应用程序变得越来越复杂并使用外部资源,您将需要处理更多的异常,使其更接近引发异常的位置,但这可以帮助您入门。 该方法仅适用于HTTP请求,不会捕获您创建的任何自定义rake任务或通过custom4ѭ执行的代码中的异常。 这是我的一个应用程序中的一个示例:
class ApplicationController < ActionController::Base
  ...
  protected

  def rescue_action_in_public (exception)
    case exception
    when ActionController::InvalidAuthenticityToken
      if request.xhr?
        render :update do |page|
          page.redirect_to \'/sessions/new/\'
        end
      else
        redirect_to \'/sessions/new/\'
      end
    when ActionController::NotImplemented
      RAILS_DEFAULT_LOGGER.info(\"ActionController::NotImplemented\\n#{request.inspect}\")
      render :nothing => true,:status => \'500 Error\'
    else
      super
    end
  end
end