Skip to content

Instantly share code, notes, and snippets.

@codesnik
Created July 24, 2015 22:21
Show Gist options
  • Save codesnik/a6f0b1c1a79e21865012 to your computer and use it in GitHub Desktop.
Save codesnik/a6f0b1c1a79e21865012 to your computer and use it in GitHub Desktop.
ruby exception extending tricks
# 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