如何使用Splat运算符将result_from用于一系列错误

问题描述

我想使用rescue_from从ActiveJob的perform方法中捕获一系列错误。我一直在使用splat运算符和rescue,如下所示:

ERRORS = [
  CustomErrorA,CustomErrorB,# ...
].freeze

def perform()
  # implementation
rescue *ERRORS => e
  handle_error(e)
end

我想做类似的事情:

rescue_from(*ERRORS,with: :handle_error)

# or alternatively

rescue_from *ERRORS do |e|
  handle_error(e)
end

是否可以通过这种方式使用splat运算符?还是必须保留rescue块才能捕获数组中的所有错误?还有我不知道的更好的方法吗?

解决方法

rescue_from将处理程序与异常类相关联,但仍必须使用rescue_with_handler来调用它,因此实现应为:

require 'active_support/rescuable'

class Test
  include ActiveSupport::Rescuable

  class CustomErrorA < StandardError; end
  class CustomErrorB < StandardError; end

  ERRORS = [CustomErrorA,CustomErrorB]

  rescue_from *ERRORS,with: :handle_error

  def handle_error
    puts "something is borked"
  end

  def rescue_test
    raise Test::CustomErrorA
  rescue *ERRORS => e
    rescue_with_handler e
  end

end

tt = Test.new
tt.rescue_test

它可以工作,但是并不能真正为您购买已经使用过的东西。