[英]Exception is only caught with `rescue` at the end of the line but not when using a `begin rescue` block
I have a statement that fails: 我的声明失败了:
result = service.load_data()
Now the following suppresses the error and I can then check for nil
现在以下抑制错误,然后我可以检查nil
result = service.load_data() rescue nil
But when I do the following the initial error is thrown right up to the UI and I don't get the details
of the exception. 但是当我执行以下操作时,初始错误会被抛到UI,我不会得到异常的details
。
begin
result = service.load_data()
rescue => details
logger.fatal "Failed to load the data: #{details}"
end
I am sure there is a silly detail I must be missing but I can't seem to spot the problem here. 我确信我必须缺少一个愚蠢的细节,但我似乎无法在这里发现问题。 So why isn't the rescue
block invoked? 那么为什么不调用rescue
区?
Update: The error I got was this: 更新:我得到的错误是这样的:
getaddrinfo: nodename nor servname provided, or not known
begin
result = service.load_data()
rescue AnExceptionKlass => details # here the name is SocketError
logger.fatal "Failed to load the data: #{details}"
end
use the above. 使用上面的。
tried to replicate the error here as below: 试图在这里复制错误,如下所示:
require 'net/http'
Net::HTTP.start('http://www.google.com') do |http|
response = http.get('/')
puts response
end
#=> getaddrinfo: No such host is known. (SocketError)
Fixed it as below: 修正如下:
require 'net/http'
begin
htt = Net::HTTP.start('http://www.google.com')
response = htt.get('/')
puts response
rescue SocketError => details # or the Exception class name may be SocketError
p "Failed to load the data: #{details}"
end
#=> "Failed to load the data: getaddrinfo: No such host is known. "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.