Skip to content

Instantly share code, notes, and snippets.

@mguinada
Forked from rks/gist:2577339
Created October 31, 2020 20:46
Show Gist options
  • Save mguinada/bd2df384b3bbf2a97a10f16a7a107cd3 to your computer and use it in GitHub Desktop.
Save mguinada/bd2df384b3bbf2a97a10f16a7a107cd3 to your computer and use it in GitHub Desktop.
Wrapping exceptions in Ruby
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment