Skip to content

Commit 505e8c3

Browse files
committed
fix json marshal of errkit.ErrX
1 parent e31b5cc commit 505e8c3

File tree

2 files changed

+27
-13
lines changed

2 files changed

+27
-13
lines changed

errkit/errors.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,21 @@ func (e *ErrorX) append(errs ...error) {
5959
}
6060
}
6161

62+
func (e ErrorX) MarshalJSON() ([]byte, error) {
63+
tmp := []string{}
64+
for _, err := range e.errs {
65+
tmp = append(tmp, err.Error())
66+
}
67+
m := map[string]interface{}{
68+
"kind": e.kind.String(),
69+
"errors": tmp,
70+
}
71+
if len(e.attrs) > 0 {
72+
m["attrs"] = slog.GroupValue(maps.Values(e.attrs)...)
73+
}
74+
return json.Marshal(m)
75+
}
76+
6277
// Errors returns all errors parsed by the error
6378
func (e *ErrorX) Errors() []error {
6479
return e.errs
@@ -97,18 +112,6 @@ func (e *ErrorX) Is(err error) bool {
97112
return false
98113
}
99114

100-
// MarshalJSON returns the json representation of the error
101-
func (e *ErrorX) MarshalJSON() ([]byte, error) {
102-
m := map[string]interface{}{
103-
"kind": e.kind.String(),
104-
"errors": e.errs,
105-
}
106-
if len(e.attrs) > 0 {
107-
m["attrs"] = slog.GroupValue(maps.Values(e.attrs)...)
108-
}
109-
return json.Marshal(m)
110-
}
111-
112115
// Error returns the error string
113116
func (e *ErrorX) Error() string {
114117
var sb strings.Builder
@@ -158,7 +161,9 @@ func FromError(err error) *ErrorX {
158161

159162
// New creates a new error with the given message
160163
func New(format string, args ...interface{}) *ErrorX {
161-
return &ErrorX{errs: []error{fmt.Errorf(format, args...)}}
164+
e := &ErrorX{}
165+
e.append(fmt.Errorf(format, args...))
166+
return e
162167
}
163168

164169
// Msgf adds a message to the error

errkit/errors_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package errkit
22

33
import (
4+
"encoding/json"
45
"testing"
56

67
"github.com/pkg/errors"
@@ -105,3 +106,11 @@ func TestErrKindCheck(t *testing.T) {
105106
require.True(t, errx.kind.Is(ErrKindNetworkPermanent), "expected to be able to find the original error")
106107
})
107108
}
109+
110+
func TestMarshalError(t *testing.T) {
111+
x := New("port closed or filtered").SetKind(ErrKindNetworkPermanent)
112+
wrapped := Wrap(x, "this is a wrapped error")
113+
marshalled, err := json.Marshal(wrapped)
114+
require.NoError(t, err, "expected to be able to marshal the error")
115+
require.Equal(t, `{"errors":["port closed or filtered","this is a wrapped error"],"kind":"network-permanent-error"}`, string(marshalled))
116+
}

0 commit comments

Comments
 (0)