Created
October 20, 2017 09:18
-
-
Save sugamasao/ab27cf0a5b4d88dfb8fb78e7096e7640 to your computer and use it in GitHub Desktop.
Exception#cause
This file contains 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
=begin | |
https://docs.ruby-lang.org/ja/latest/class/Exception.html#I_CAUSE | |
[START] -> foo error. | |
[FooError-0] : foo error. -> ["exception_sample.rb:19:in `rescue in run'", "exception_sample.rb:16:in `run'", "exception_sample.rb:37:in `<main>'"] | |
[BarError-1] : bar error. -> ["exception_sample.rb:9:in `rescue in run'", "exception_sample.rb:6:in `run'", "exception_sample.rb:17:in `run'", "exception_sample.rb:37:in `<main>'"] | |
[ZeroDivisionError-2] : divided by 0 -> ["exception_sample.rb:7:in `/'", "exception_sample.rb:7:in `run'", "exception_sample.rb:17:in `run'", "exception_sample.rb:37:in `<main>'"] | |
[END] | |
=end | |
class FooError < StandardError;end | |
class BarError < StandardError;end | |
class Bar | |
def run | |
begin | |
100 / 0 | |
rescue => e | |
raise BarError, 'bar error.' | |
end | |
end | |
end | |
class Foo | |
def run | |
begin | |
Bar.new.run | |
rescue => e | |
raise FooError, 'foo error.' | |
end | |
end | |
end | |
f = Foo.new | |
def dig_exception(e, count: 0, &block) | |
yield e, count | |
if e.cause.nil? | |
return | |
else | |
count+=1 | |
dig_exception(e.cause, count: count, &block) | |
end | |
end | |
begin | |
f.run | |
rescue => e | |
puts "[START] -> #{ e.message }" | |
dig_exception(e) do |ex, index| | |
puts "[#{ ex.class }-#{ index }] : #{ ex.message } -> #{ex.backtrace}" | |
end | |
puts "[END]" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment