Created
July 24, 2015 22:21
-
-
Save codesnik/a6f0b1c1a79e21865012 to your computer and use it in GitHub Desktop.
ruby exception extending tricks
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
# we can extend exception with arbitrary modules, add metadata and so on | |
# we can then rescue from that module! | |
module MyAttr | |
attr_accessor :my_attr | |
end | |
class MyException < StandardError | |
end | |
def foo | |
raise MyException, "messsage" | |
rescue MyException => e | |
e.extend MyAttr | |
e.my_attr = "hahaha it works!" | |
raise | |
end | |
begin | |
foo | |
rescue MyAttr => e | |
puts e.message | |
puts e.my_attr | |
puts e.class | |
puts e.backtrace | |
end | |
# result: | |
# messsage | |
# hahaha it works! | |
# MyException | |
# test_exception_extending.rb:12:in `foo' | |
# test_exception_extending.rb:20:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment