【问题标题】:Is there any good best practices for exception handling in rails?Rails 中的异常处理有什么好的最佳实践吗?
【发布时间】:2010-05-27 08:45:17
【问题描述】:

我目前在 Rails 2.3.5 上,我正在尝试在我的应用程序中尽可能简洁地使用 rescue_from 异常。

我的 ApplicationController 救援现在看起来像这样:

  rescue_from Acl9::AccessDenied, :with => :access_denied
  rescue_from Exceptions::NotPartOfGroup, :with => :not_part_of_group
  rescue_from Exceptions::SomethingWentWrong, :with => :something_went_wrong
  rescue_from ActiveRecord::RecordNotFound, :with => :something_went_wrong
  rescue_from ActionController::UnknownAction, :with => :something_went_wrong
  rescue_from ActionController::UnknownController, :with => :something_went_wrong
  rescue_from ActionController::RoutingError, :with => :something_went_wrong

我还希望能够捕获上面未列出的任何异常。有没有推荐的方式来写我的救援?

谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以捕获更多通用异常,但您必须将它们放在顶部,如 here 所解释的那样

    例如,要捕获所有其他异常,您可以这样做

    rescue_from Exception, :with => :error_generic
    rescue_from ... #all others rescues
    

    但如果您这样做,请确保您至少记录异常,否则您将永远不知道您的应用出了什么问题:

    def error_generic(exception)
      log_error(exception)
      #your rescue code
    end
    

    此外,您可以为一个处理程序在一行中定义多个异常类:

      rescue_from Exceptions::SomethingWentWrong, ActiveRecord::RecordNotFound, ... , :with => :something_went_wrong
    

    【讨论】:

      【解决方案2】:

      也许exception notifier插件可以帮到你

      【讨论】:

        【解决方案3】:

        你可以像这样在 ApplicationController 中定义一个钩子方法:

        def rescue_action_in_public(exception)   
          case exception
        
          when ActiveRecord::RecordNotFound, ActionController::UnknownAction, ActionController::RoutingError
            redirect_to errors_path(404), :status=>301
          else
            redirect_to errors_path(500)
          end
        end
        

        【讨论】:

          【解决方案4】:

          我最近发布了一个 rails 3 gem (egregious),它将使用 rescue_from 捕获常见异常,并为 html、json 和 xml 提供明确定义的 http 状态代码和错误响应。

          默认情况下,它会尝试做正确的事情。您可以在初始化程序中添加或更改任何异常及其状态代码。

          这可能适合也可能不适合您的需求。 https://github.com/voomify/egregious

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-01-03
            • 1970-01-01
            • 2013-01-13
            • 2011-12-09
            • 1970-01-01
            • 2015-02-13
            • 2011-11-16
            相关资源
            最近更新 更多