在rails中进行异常处理是否有任何良好的最佳实践?

时间:2010-05-27 08:45:18

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

我目前正在使用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

我还希望能够捕获上面没有列出的任何例外情况。有推荐的方式我应该写我的救援吗?

由于

4 个答案:

答案 0 :(得分:5)

您可以捕获更多通用异常,但必须将它们放在最前面,如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

答案 1 :(得分:1)

也许exception notifier插件可以帮助你某种方式

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

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

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

相关问题