【发布时间】:2015-05-28 15:36:51
【问题描述】:
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
但这意味着它将以与所有控制器相同的方式处理指定的异常。
如果我想根据引发异常的方法以不同的方式处理异常类型怎么办,示例:
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
我有以下问题:
这是否也可以通过使用 :rescue_from 来完成(可以传入任何类型的选项)?
如果没有,有没有更好的办法来处理这种情况?
(有点离题,但是)通常以不同的方法以不同的方式处理相同类型的错误是一种不好的做法吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 exception-handling