2010-05-27 73 views
2

我目前在Rails 2.3.5上,并且尽量在我的应用程序中尝试使用rescue_from异常。在rails中有什么好的最佳实践来处理异常?

我的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 

我也希望能够赶上上面没有列出任何异常。有建议的方式,我应该写我的救援?

感谢

回答

5

您可以捕捉更通用的异常,但是你必须把它们在顶部,如expained 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

你可以在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 
0

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

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

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

相关问题