Skip to content

Commit

Permalink
Merge pull request #342 from husio/exception_unwrap
Browse files Browse the repository at this point in the history
implement Exception.Unwrap method
  • Loading branch information
serprex authored Oct 14, 2024
2 parents 15ff3b2 + 133e888 commit e52bd23
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
19 changes: 19 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,25 @@ func (e *Exception) Error() string {
return fmt.Sprintf("%s: %s: %s", e.Code, e.Name, msg)
}

// Unwrap implements errors.Unwrap interface.
func (e *Exception) Unwrap() []error {
if e == nil {
return nil
}
// Flatten error tree by collecting all error codes.
// Only check error codes since only they can be compared using errors.Is.
// Dynamically created Exceptions are not relevant for this functionality.
return e.collectCodes(nil)
}

func (e *Exception) collectCodes(codes []error) []error {
result := append(codes, e.Code)
for _, next := range e.Next {
result = next.collectCodes(result)
}
return result
}

// AsException finds first *Exception in err chain.
func AsException(err error) (*Exception, bool) {
var e *Exception
Expand Down
27 changes: 27 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ch

import (
"context"
"errors"
"os"
"testing"

Expand Down Expand Up @@ -87,3 +88,29 @@ func TestDial(t *testing.T) {
require.True(t, IsErr(err, proto.ErrUnknownDatabase))
})
}

func TestExceptionUnwrap(t *testing.T) {
flat := &Exception{
Code: proto.ErrReadonly,
Name: "foo",
Message: "bar",
Next: nil,
}

if !errors.Is(flat, proto.ErrReadonly) {
t.Fatal("flat exception must be the error code it represents")
}

nested := &Exception{
Code: proto.ErrAborted,
Name: "foo",
Message: "bar",
Next: []Exception{*flat},
}
if !errors.Is(nested, proto.ErrAborted) {
t.Fatal("nested exception must be the error code it represents")
}
if !errors.Is(nested, proto.ErrReadonly) {
t.Fatal("nested exception must be the error code it wraps")
}
}

0 comments on commit e52bd23

Please sign in to comment.