Skip to content

Instantly share code, notes, and snippets.

@noahgibbs
Created December 16, 2016 16:21
Show Gist options
  • Save noahgibbs/13b91f35a85318e836f627758c26da4c to your computer and use it in GitHub Desktop.
Save noahgibbs/13b91f35a85318e836f627758c26da4c to your computer and use it in GitHub Desktop.
Sample Ruby code with nested exceptions - use Ruby 2.3.0 or higher
class LibraryError < RuntimeError; end
class AppError < RuntimeError; end
# Library code
def library_call
begin
1/0
rescue
raise LibraryError.new("Something went wrong")
end
end
# App code
def app_call
library_call
rescue LibraryError
raise AppError.new("The Library had an error")
end
begin
app_call
rescue => e
puts "Error: #{e.inspect}"
print "\n"
puts "Caused by: #{e.cause.inspect}"
puts "Which was caused by: #{e.cause.cause.inspect}"
puts "Which was caused by (nothing): #{e.cause.cause.cause.inspect}"
print "\n"
puts "A message: #{e.cause.cause.message}"
print "\n"
puts "A backtrace:\n #{e.cause.backtrace.join("\n ")}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment