我有以下代码:
begin
site = RedirectFollower.new(url).resolve
rescue => e
puts e.to_s
return false
end
会抛出错误,如:
the scheme http does not accept registry part: www.officedepot.com;
the scheme http does not accept registry part: ww2.google.com/something;
Operation timed out - connect(2)
如何为the scheme http does not accept registry part
之类的所有错误添加其他救援?
因为我想做的不仅仅是打印错误并在这种情况下返回false。
答案 0 :(得分:13)
这取决于。
我看到三个异常描述是不同的。异常类型是否也有所不同?
如果是这样你可以像这样编写你的代码:
begin
site = RedirectFollower.new(url).resolve
rescue ExceptionType1 => e
#do something with exception that throws 'scheme http does not...'
else
#do something with other exceptions
end
如果异常类型相同,那么您仍然会有一个救援区块,但会根据正则表达式决定做什么。也许是这样的事情:
begin
site = RedirectFollower.new(url).resolve
rescue Exception => e
if e.message =~ /the scheme http does not accept registry part/
#do something with it
end
end
这有帮助吗?
答案 1 :(得分:6)
如果'方案http不接受注册表部分',请检查什么是异常类(您可以通过puts e.class
执行此操作)。我认为这不是'操作超时 - 连接(2)'
然后:
begin
.
rescue YourExceptionClass => e
.
rescue => e
.
end
答案 2 :(得分:1)
重要说明:使用通配符进行救援,默认为StandardError。它不会挽救每一个错误。
例如,SignalException: SIGTERM
不会使用rescue => error
获救。您必须专门使用rescue SignalException => e
。