2010-05-27 70 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

相關問題