我正在尝试创建一个模块来处理我在include中application_controller.rb中的API错误。这是我的模块的self.included函数。
def self.included(clazz)
clazz.class_eval do
rescue_from ActiveRecord::RecordNotFound do |e|
respond(:record_not_found, 404, e.message)
end
rescue_from ActiveRecord::RecordInvalid do |e|
respond(:record_invalid, 422, e.record.errors.full_messages)
end
rescue_from ActionController::ParameterMissing do |e|
respond(:bad_request, 400, e.message)
end
rescue_from StandardError do |e|
respond(:standard_error, 500, e.message)
end
end
end我遇到的问题是,StandardError捕获所有错误,包括我在其他rescue_from块中定义的其他错误。
我想要实现这样的目标:
begin
rescue ActiveRecord::RecordNotFound => e
rescue ActiveRecord::RecordInvalid => e
rescue ActionController::ParameterMissing => e
rescue StandardError => e
end谢谢你提前帮忙。
发布于 2020-05-12 23:37:03
我会将其重构为单个rescue_from,然后通过检查e.class向下钻取
rescue_from StandardError do |e|
case e.class
when ActiveRecord::RecordNotFound
respond(:record_not_found, 404, e.message)
when ActiveRecord::RecordInvalid
respond(:record_invalid, 422, e.record.errors.full_messages)
when ActionController::ParameterMissing
respond(:record_not_found, 400, e.message)
else
respond(:standard_error, 500, e.message)
end
end发布于 2020-05-13 01:01:26
问题是rescue_from处理程序是
处理程序是继承的。它们从右到左、从下到上、从上到上都会被搜索。
这意味着这些块是按反向顺序执行的,因此您的4个rescue_from看起来更像:
begin
rescue StandardError => e
rescue ActionController::ParameterMissing => e
rescue ActiveRecord::RecordInvalid => e
rescue ActiveRecord::RecordNotFound => e
end而不是。添加的最后一个处理程序是第一个执行的,这一事实允许子控制器之类的东西覆盖父控制器中的处理程序。因此,要修复,只需反转定义rescue_from块的顺序,事情就应该按照您的意愿工作。
https://stackoverflow.com/questions/61763700
复制相似问题