gpt4 book ai didi

ruby-on-rails - rails 中的异常处理有什么好的最佳实践吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:25:24 26 4
gpt4 key购买 nike

我目前使用的是 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

我还希望能够捕获上面未列出的任何异常。是否有推荐的方式来编写我的救援?

谢谢

最佳答案

您可以捕获更多通用异常,但您必须将它们放在顶部,如所解释的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

关于ruby-on-rails - rails 中的异常处理有什么好的最佳实践吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2919648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com