gpt4 book ai didi

ruby-on-rails - Rails - rescue_from 异常根据引发异常的方法以不同方式处理异常类型

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

Rails 的 :rescue_from 接受一个特定的异常类型和一个方法作为参数,如下所示:

class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, with: :deny_access # self defined exception
rescue_from ActiveRecord::RecordInvalid, with: :show_errors

rescue_from 'MyAppError::Base' do |exception|
render xml: exception, status: 500
end

protected
def deny_access
...
end

def show_errors(exception)
exception.record.new_record? ? ...
end
end

但这意味着它将在整个 Controller 中以相同的方式处理指定的异常。

如果我想根据引发异常的方法以不同方式处理异常类型怎么办,示例:

class MyController < ActionController::Base

def method_1
# Do Something
rescue MyCustomError => e
handle_exception_for_method_1(e)
end

def method_2
# Do Something
rescue MyCustomError => e
handle_exception_for_method2(e)
end

protected

def handle_exception_for_method_1(exception)
# Do Something
end

def handle_exception_for_method_2(exception)
# Do Something
end

end

我有以下问题:

  1. 这也可以通过使用 :rescue_from 来完成吗(可以传入任何类型的选项)?

  2. 如果没有,有没有更好的解决办法来处理这种情况?

  3. (有点跑题了)一般来说,在不同的方法中以不同的方式处理同一类型的错误是不是一种不好的做法?

最佳答案

Rails 提供对 controller and action names 的访问通过 controller_nameaction_name 方法。您可以使用它根据引发异常的方法以不同方式处理异常。

例子:

class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordInvalid, with: :show_errors

protected

def show_errors
if action_name == "create"
...
elsif action_name == ...
...
end
end

关于ruby-on-rails - Rails - rescue_from 异常根据引发异常的方法以不同方式处理异常类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30511125/

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