捕获大量错误并将所有被捕获的错误放入常量
Catching a lot of errors and putting all the errors being caught into a constant
有没有办法在 rescue 子句中将所有错误放入一个数组中,如果错误在数组中,则从那里调用它们?
例如:
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)
如何才能成功挽救多个错误,而不是将它们全部放在救援线上并使其看起来很糟糕?
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]
有没有办法在 rescue 子句中将所有错误放入一个数组中,如果错误在数组中,则从那里调用它们?
例如:
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)
如何才能成功挽救多个错误,而不是将它们全部放在救援线上并使其看起来很糟糕?
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]