我有一個簡單的異常處理塊異常在Ruby中處理 - 它會重新開始 - 如果去搶救
begin
<connect to network and make a request>
rescue
<comes here if it didnt connect/whatever other error>
end
我想修改它這樣,如果涉及到救援電話開始。給5次嘗試。如果仍不能連接 - 走出塊
我有一個簡單的異常處理塊異常在Ruby中處理 - 它會重新開始 - 如果去搶救
begin
<connect to network and make a request>
rescue
<comes here if it didnt connect/whatever other error>
end
我想修改它這樣,如果涉及到救援電話開始。給5次嘗試。如果仍不能連接 - 走出塊
計數器加retry
,直到該計數器命中值:
MAX_RETRIES = 5
retries = 0
begin
do_something
rescue ex
if retries += 1 <= MAX_RETRIES
retry
else
raise ex
end
end
你可能要重新上只有一些與網絡有關的例外情況,如超時。有時一個未被發現或被禁止的東西總是會被除去,除非你在這個變化之前進行投票。
這應該這樣做:
5.times do |i|
begin
1/0
rescue
puts 'Try #{i+1} failed ...'
next
end
puts 'Try #{i+1} success.'
break
end
寫一個方法來連接到網絡這樣
def connect_to_server(retry_count)
begin
retry_count += 1
<connect to network and make a request>
rescue
if(retry_count <= 5)
connect_to_server(retry_count)
end
end
end
調用該方法
connect_to_server(0)
爲什麼使用開始resue塊? – Nithin