diff --git a/Gemfile.lock b/Gemfile.lock index 96ee7e6..d9d88fd 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - leopard (0.1.7) + leopard (0.2.2) concurrent-ruby (~> 1.1) dry-configurable (~> 1.3) dry-monads (~> 1.9) diff --git a/lib/leopard/errors.rb b/lib/leopard/errors.rb index a66b24c..985a373 100644 --- a/lib/leopard/errors.rb +++ b/lib/leopard/errors.rb @@ -2,7 +2,24 @@ module Rubyists module Leopard - class Error < StandardError; end + class LeopardError < StandardError + def initialize(...) + super + set_backtrace(caller) + end + + def backtrace + # If the backtrace is nil, return an empty array + orig = (super || [])[0..3] + # If the backtrace is less than 4 lines, return it as is + return orig if orig.size < 4 + + # Otherwise, add a note indicating truncation + orig + ['... (truncated by Leopard)'] + end + end + + class Error < LeopardError; end class ConfigurationError < Error; end class ResultError < Error; end end diff --git a/test/lib/errors.rb b/test/lib/errors.rb new file mode 100644 index 0000000..f772f7b --- /dev/null +++ b/test/lib/errors.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +require 'helper' +require 'leopard/errors' + +describe 'Rubyists::Leopard::Errors' do + def level1 + level2 + end + + def level2 + level3 + end + + def level3 + raise Rubyists::Leopard::Error, 'Error boom' + end + + it 'truncates backtrace to 5 items' do + err = assert_raises(Rubyists::Leopard::Error) { level1 } + + bt = err.backtrace + + assert_equal 5, bt.count + assert_equal '... (truncated by Leopard)', bt.last + refute(bt.any? { |line| line.include?("in 'level1'") }) + end +end