Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | 例外 | 例外のリトライ

概要

例外のリトライ

詳細

例外発生時に処理をリトライすることが可能です。

サンプルコード

# encoding: Windows-31J
require "pp"

class ConnectionError < StandardError
end

@counter = 0
def connect_server()
  @counter = @counter + 1
  if (@counter == 5)
    return "success connection"
  else
    raise ConnectionError,"fail connection try-count:#{@counter}"
  end
end

begin
  puts @counter
  puts connect_server
rescue
  puts $!.to_s
  retry
end

出力

0
fail connection try-count:1
1
fail connection try-count:2
2
fail connection try-count:3
3
fail connection try-count:4
4
success connection