0
我想在Rails 3中處理自己的異常。在Rails 3中處理自定義異常和路由錯誤的最佳過程是什麼?Rails 3中的異常處理3
我想在Rails 3中處理自己的異常。在Rails 3中處理自定義異常和路由錯誤的最佳過程是什麼?Rails 3中的異常處理3
您可以處理您的自定義異常如下: 在應用控制器,增加follwing:
rescue_from Exception, :with => :handle_exception
def not_found
render :template => "shared/not_found", :status => 404
end
private
def handle_exception(exception)
case exception
when CanCan::AccessDenied
authenticate_user!
when ActiveRecord::RecordNotFound
not_found
else
internal_server_error(exception)
end
end
def internal_server_error(exception)
render :template => "shared/internal_server_error", :status => 500
end
現在,在你的方法,你可以提高錯誤或異常如:
def method_name
# raise exception_name, "message on exception"
raise ArgumentError, "missing some param"
end
你可以還通過添加路由來捕獲路由錯誤,如下所示:
match "*any", :to => "application#not_found"
注意:您應該在您的route.rb末尾添加上述路線