Skip to content

Instantly share code, notes, and snippets.

@adeubank
Created August 14, 2018 16:06
Show Gist options
  • Save adeubank/efbfd9336c521f5b44996bd3c0054393 to your computer and use it in GitHub Desktop.
Save adeubank/efbfd9336c521f5b44996bd3c0054393 to your computer and use it in GitHub Desktop.
def my_fun
vals = []
(1..5).each do |i|
puts "my_fun i=#{i}"
begin
handle_catchable_errors do
vals << unsafe_fun(i)
end
rescue KnownError => e
puts "my_fun caught known error. #{e.class} #{e}. continuing"
next
rescue UnsafeError => e
puts "my_fun caught unsafe error. #{e.class} #{e}. continuing"
next
end
end
end
def handle_catchable_errors(max_tries: 5)
attempt ||= 0
attempt += 1
puts "handle_catchable_errors attempt=#{attempt}"
yield
rescue KnownError => e
puts "Unsafe error ok! #{e}"
if attempt >= max_tries
raise e
else
retry
end
rescue UnsafeError => e
puts "Unsafe error ok! #{e}"
if attempt >= max_tries
raise e
else
retry
end
rescue RandomError => e
puts "RandomError not ok! #{e}"
raise e
end
def unsafe_fun(i)
puts "unsafe_fun i=#{i}"
if i < 2
raise KnownError.new("Known #{i}")
end
if i % 2 == 0
raise UnsafeError.new("Unsafe #{i}")
end
roll = rand(1..10)
if (roll > 8)
raise RandomError.new("Random #{i} roll=#{roll}")
end
puts "Safe now i=#{i}"
return i * -1
end
class UnsafeError < StandardError
end
class RandomError < StandardError
end
class KnownError < StandardError
end
my_fun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment