Skip to content

Commit

Permalink
[e] fix creation of error from empty error
Browse files Browse the repository at this point in the history
Change-Id: Idccb59a1364ed49f36948a0b2c3f37519e02d6aa
  • Loading branch information
xobotyi committed Dec 3, 2024
1 parent 9467550 commit 023053c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
8 changes: 8 additions & 0 deletions e/err.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ func NewFrom(reason string, wrapped error, f ...fields.Field) *Err {
// will not return origin error. Passing nil to this function will result with
// empty error.
func From(origin error, f ...fields.Field) *Err {
if origin == nil {
origin = errors.New("error(nil)") //nolint:err113
}

return &Err{
errs: []error{origin},
fields: f,
Expand All @@ -46,6 +50,10 @@ func From(origin error, f ...fields.Field) *Err {
//
// e.New("e1").Wrap(errors.New("e2")) // e1: e2
func (e *Err) Wrap(err error, f ...fields.Field) *Err {
if err == nil {
err = errors.New("error(nil)") //nolint:err113
}

return &Err{
errs: []error{e, err},
fields: f,
Expand Down
19 changes: 18 additions & 1 deletion e/err_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ func TestErr(t *testing.T) {
in: nil,
expected: "(*e.Err)(nil)",
},
{
name: "nil wrapping fields",
in: (*e.Err)(nil).WithField("foo", "bar"),
expected: "(*e.Err)(nil) (foo=bar)",
},
{
name: "empty",
in: &e.Err{},
Expand Down Expand Up @@ -107,6 +112,16 @@ func TestErr(t *testing.T) {
in: e.From(errors.New("error"), fields.F("key", "value")), //nolint:err113
expected: "error (key=value)",
},
{
name: "from nil error",
in: e.From(nil),
expected: "error(nil)",
},
{
name: "from nil with fields",
in: e.From(nil, fields.F("key", "value")),
expected: "error(nil) (key=value)",
},
{
name: "empty with fields",
in: (&e.Err{}).WithField("foo", "bar"),
Expand All @@ -127,9 +142,11 @@ func TestErr(t *testing.T) {

assert.NotSame(t, e1, e1.Wrap(e2))
assert.NotSame(t, e2, e1.Wrap(e2))
assert.NoError (t, errors.Unwrap(e1.Wrap(e2)), "errors unwrap returns nil")
assert.NoError(t, errors.Unwrap(e1.Wrap(e2)), "errors unwrap returns nil")
assert.Equal(t, "e1 (f1=v1): e2 (f2=v2)", e1.Wrap(e2).Error())
assert.Equal(t, "e1 (f1=v1) (f3=v3): e2 (f2=v2)", e1.Wrap(e2, fields.F("f3", "v3")).Error())

assert.Equal(t, "e1 (f1=v1): error(nil)", e1.Wrap(nil).Error())
})

t.Run(".Is()", func(t *testing.T) {
Expand Down

0 comments on commit 023053c

Please sign in to comment.