Skip to content

Instantly share code, notes, and snippets.

@rks
Created May 2, 2012 15:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rks/2577339 to your computer and use it in GitHub Desktop.
Save rks/2577339 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
@jbodah
Copy link

jbodah commented Oct 7, 2014

+1 for this!

Some tweaks:

class ClientError < StandardError
  def initialize(e = nil)
    super e
    # Preserve the original exception's data if provided
    if e && e.is_a?(Exception)
      set_backtrace e.backtrace
      message.prepend "#{e.class}: "
    end
  end
end

@lailsonbm
Copy link

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