【问题标题】:Catching a lot of errors and putting all the errors being caught into a constant捕获大量错误并将所有被捕获的错误放入一个常量中
【发布时间】:2017-01-02 10:53:08
【问题描述】:

如果错误在数组中,有没有办法在救援子句中将所有错误放入一个数组并从那里调用它们?

例如:

FATAL_ERRORS = %w(Mechanize::ResponseCodeError RestClient::ServiceUnavailable OpenSSL::SSL::SSLError RestClient::BadGateway)

begin
  # Do some cool stuff
rescue FATAL_ERRORS => e
  puts "Exiting #{e}"

我尝试过的:

我已经尝试从当前线程中抓取错误:

FATAL_ERRORS = Thread.current[:errors] ||= %w(Mechanize::ResponseCodeError RestClient::ServiceUnavailable OpenSSL::SSL::SSLError RestClient::BadGateway)

begin
  # Do some cool stuff
rescue FATAL_ERRORS => e
  puts "Exiting #{e}"

我也尝试过 splat 运算符:

FATAL_ERRORS = %w(Mechanize::ResponseCodeError RestClient::ServiceUnavailable OpenSSL::SSL::SSLError RestClient::BadGateway)

begin
  # Do some cool stuff
rescue *FATAL_ERRORS => e
  puts "Exiting #{e}"

splat 和线程都产生以下异常: rescue in <main>': class or module required for rescue clause (TypeError)

我怎样才能成功地挽救多个错误,而不会将它们全部放在挽救线上并使其看起来很糟糕?

【问题讨论】:

    标签: ruby error-handling rescue


    【解决方案1】:

    splat 确实有效。问题在于您使FATAL_ERRORS 保持不变的方式。使用%w 表示法,它将值转换为字符串:

     %w(Mechanize::ResponseCodeError)
     => ["Mechanize::ResponseCodeError"] # Note the string value instead of class constant.
    

    试试

    FATAL_ERRORS = [Mechanize::ResponseCodeError, RestClient::ServiceUnavailable, OpenSSL::SSL::SSLError, RestClient::BadGateway]
    

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 2023-03-28
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      相关资源
      最近更新 更多