Skip to content

Commit

Permalink
Merge pull request #5 from telebugs/unwrap-errors
Browse files Browse the repository at this point in the history
Add the WrappedError class
  • Loading branch information
kyrylo committed Jun 6, 2024
2 parents 67145bc + 7d1aefa commit bb89286
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/telebugs.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
require_relative "telebugs/version"
require_relative "telebugs/config"
require_relative "telebugs/promise"
require_relative "telebugs/wrapped_error"

module Telebugs
# The general error that this library uses when it wants to raise.
Expand Down
22 changes: 22 additions & 0 deletions lib/telebugs/wrapped_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module Telebugs
# WrappedError unwraps an error and its causes up to a certain depth.
class WrappedError
MAX_NESTED_ERRORS = 3

def initialize(error)
@error = error
end

def unwrap
error_list = []
error = @error

while error && error_list.size < MAX_NESTED_ERRORS
error_list << error
error = error.cause
end

error_list
end
end
end
41 changes: 41 additions & 0 deletions test/test_wrapped_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# frozen_string_literal: true

require "test_helper"

class TestWrappedError < Minitest::Test
def test_unwraps_errors_without_a_cause
error = StandardError.new
wrapped = Telebugs::WrappedError.new(error)

assert_equal [error], wrapped.unwrap
end

def test_unwraps_no_more_than_3_nested_errors
begin
raise "error 1"
rescue => _
begin
raise "error 2"
rescue => _
begin
raise "error 3"
rescue => e3
begin
raise "error 4"
rescue => e4
begin
raise "error 5"
rescue => e5
end
end
end
end
end

wrapped = Telebugs::WrappedError.new(e5)
unwrapped = wrapped.unwrap

assert_equal 3, unwrapped.size
assert_equal [e5, e4, e3], unwrapped
end
end

0 comments on commit bb89286

Please sign in to comment.