【问题标题】:How to use rescue_from for an array of errors with splat operator如何使用rescue_from 处理splat 运算符的一系列错误
【发布时间】:2020-08-11 10:51:28
【问题描述】:

我想使用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 块才能捕获数组中的所有错误?有没有更好的方法我不知道?

【问题讨论】:

  • 我不认为你可以列出救援清单。也许这是一个设计问题:如果错误是相关的,为什么不从公共基类继承它们,并拯救基类?
  • 我猜这可能行得通,你能写下这个解决方案作为答案吗?
  • 这不是你原来问题的真正答案,只是OOP的一个基本原理,所以我有点不愿意把它写成一个解决方案
  • 您总是可以寻求“不可能,改为这样做”的解决方案。我同意不是直接解决问题本身,而是解决问题:)

标签: ruby-on-rails ruby


【解决方案1】:

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

它有效,但它并没有真正为你购买任何东西,而不是你已经在使用的东西。

【讨论】:

    猜你喜欢
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 2016-02-24
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 2021-05-11
    相关资源
    最近更新 更多