Skip to content

Commit

Permalink
Add the WrappedError class
Browse files Browse the repository at this point in the history
  • Loading branch information
kyrylo committed Jun 6, 2024
1 parent 67145bc commit 65c81a4
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
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 RuntimeError, "error 1"
rescue => e1
begin
raise RuntimeError, "error 2"
rescue => e2
begin
raise RuntimeError, "error 3"
rescue => e3
begin
raise RuntimeError, "error 4"
rescue => e4
begin
raise RuntimeError, "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 65c81a4

Please sign in to comment.