为了让我的程序按预期工作,rescue_from 的顺序并不直观。我想知道为什么会这样或者我哪里出错了?
我正在尝试这个错误处理解决方案。
我的错误处理程序与 github repo 中的相同
module Error
module ErrorHandler
def self.included(clazz)
clazz.class_eval do
rescue_from ActiveRecord::RecordNotFound do |e|
respond(:record_not_found, 404, e.to_s)
end
rescue_from CustomError do |e|
respond(e.error, e.status, e.message.to_s)
end
rescue_from StandardError do |e|
respond(:standard_error, 500, e.to_s)
end
end
end
这导致我的错误始终被捕获在 StandardError
block 中,跳过 ActiveRecord::RecordNotFound
和 Custom
错误 block 。
但是,如果我切换顺序(StandardError
在执行中更高),它会正确捕获其他类型的错误。
def self.included(clazz) #includes module as a class method
clazz.class_eval do
rescue_from StandardError do |e|
respond(:standard_error, 500, e.to_s)
end
rescue_from ActiveRecord::RecordNotFound do |e|
respond(:record_not_found, 404, e.to_s)
end
rescue_from CustomError do |e|
respond(e.error, e.status, e.message.to_s)
end
end
end
为什么将 StandardError 放在顶部会起作用?
最佳答案
last declared handler has the highest priority ,因此您应该首先声明通用处理程序(例如用于 StandardError
的处理程序),然后再声明特定处理程序。
关于ruby-on-rails - 全局错误处理和包含的rescue_from的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634123/