Created
April 15, 2013 09:07
-
-
Save baya/5386883 to your computer and use it in GitHub Desktop.
exception retry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def try(title, options = { }, &p) | |
tried_times = 0 | |
max_times = options[:max_times] || 3 | |
exceptions = options[:on] || Exception | |
exceptions = [exceptions] if !exceptions.is_a?(Array) | |
rescue_text = <<-EOF | |
begin | |
# 不能用yield | |
p.call | |
rescue #{exceptions.join(',')} => e | |
log_exception(title, e) | |
retry if (tried_times += 1) < max_times | |
raise e | |
end | |
EOF | |
eval rescue_text | |
end | |
# 测试代码 | |
require 'test_helper' | |
class MsBtTest < ActiveSupport::TestCase | |
test '.try' do | |
tried_times = 0 | |
begin | |
MsBt.try('测试异常重试次数', :max_times => 3, :on => [Exception, ZeroDivisionError]) do | |
tried_times += 1 | |
10 / 0 | |
end | |
rescue Exception => e | |
assert_equal tried_times, 3 | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment