Ruby on rails rails中的异常处理有什么好的最佳实践吗?

Ruby on rails rails中的异常处理有什么好的最佳实践吗?,ruby-on-rails,ruby,exception-handling,Ruby On Rails,Ruby,Exception Handling,我目前使用的是Rails 2.3.5,我正在尝试在我的应用程序中尽可能简洁地从异常中解救您 我的ApplicationController救援现在如下所示: rescue_from Acl9::AccessDenied, :with => :access_denied rescue_from Exceptions::NotPartOfGroup, :with => :not_part_of_group rescue_from Exceptions::SomethingWe

我目前使用的是Rails 2.3.5,我正在尝试在我的应用程序中尽可能简洁地从异常中解救您

我的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
我还希望能够捕获上面没有列出的任何异常。有没有推荐我写救援的方法


谢谢

您可以捕获更多的通用异常,但您必须将它们放在顶部,如前所述

例如,要捕获所有其他异常,可以执行以下操作

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

也许插件可以在某种程度上帮助您

您可以在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

我最近发布了一个rails3gem(异常),它将使用rescue_捕获常见异常,并为html、json和xml提供定义良好的http状态码和错误响应

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

这可能适合您的需要,也可能不适合您的需要