Created
May 2, 2012 15:12
-
-
Save rks/2577339 to your computer and use it in GitHub Desktop.
Wrapping exceptions in Ruby
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
class CustomError < StandardError | |
def initialize(e = nil) | |
super e | |
set_backtrace e.backtrace if e | |
end | |
end | |
def run | |
r = Runner.new | |
r.fail | |
end | |
class Runner | |
def fail | |
_fail | |
end | |
def _fail | |
service = RunnerService.new | |
service.fail | |
rescue StandardError => e | |
raise CustomError.new(e) | |
end | |
end | |
class RunnerService | |
def fail | |
_fail | |
end | |
def _fail | |
raise StandardError.new('Service failed') | |
end | |
end | |
begin | |
run | |
rescue CustomError => e | |
puts e.message | |
puts ' ' + e.backtrace.join("\n ") | |
end |
Fortunately, this is not needed anymore from Ruby 2.1 on:
http://devblog.avdi.org/2013/12/25/exception-causes-in-ruby-2-1/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1 for this!
Some tweaks: