定義ApplicationController#rescue_in_public(exception)
並將您的自定義處理代碼放在那裏。
這增強了Rails的默認異常處理在頂層 - 生成HTTP響應權利之前。隨着Rails應用程序的複雜性增加並使用外部資源,將會有更多的異常讓您更加接近拋出異常的位置,但這可以讓您開始。
這種方法只能在HTTP請求工作,不會趕上在您創建通過rails runner
執行任何定製耙任務或代碼例外。
下面是從我的應用程序一個例子:
class ApplicationController < ActionController::Base
...
protected
def rescue_action_in_public (exception)
case exception
when ActionController::InvalidAuthenticityToken
if request.xhr?
render :update do |page|
page.redirect_to '/sessions/new/'
end
else
redirect_to '/sessions/new/'
end
when ActionController::NotImplemented
RAILS_DEFAULT_LOGGER.info("ActionController::NotImplemented\n#{request.inspect}")
render :nothing => true, :status => '500 Error'
else
super
end
end
end
在Ruby中,他們被稱爲例外。 – steenslag 2011-05-19 21:26:04
是否有捕獲_all_異常的標準方法? (沒有嘗試/到處捕捉) – helion3 2011-05-19 21:36:03