rescue_from StandardError 覆盖其他rescue_from 块

Can*_*yer 1 ruby ruby-on-rails ruby-on-rails-6

我正在尝试创建一个模块来处理我includeapplication_controller.rb. 这是我的模块的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
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是StandardError捕获所有错误,包括我在其他块中定义的其他错误rescue_from

我想实现这样的目标:

begin

rescue ActiveRecord::RecordNotFound => e

rescue ActiveRecord::RecordInvalid => e

rescue ActionController::ParameterMissing => e

rescue StandardError => e

end
Run Code Online (Sandbox Code Playgroud)

我在这里先向您的帮助表示感谢。

max*_*ner 7

我会将其重构为一个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
Run Code Online (Sandbox Code Playgroud)