Skip to content

Commit

Permalink
Merge pull request #426 from projectdiscovery/fix-errkit-marshal-err
Browse files Browse the repository at this point in the history
fix json marshal of errkit.ErrX
  • Loading branch information
tarunKoyalwar authored May 30, 2024
2 parents e31b5cc + 505e8c3 commit c6364a3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
31 changes: 18 additions & 13 deletions errkit/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,21 @@ func (e *ErrorX) append(errs ...error) {
}
}

func (e ErrorX) MarshalJSON() ([]byte, error) {
tmp := []string{}
for _, err := range e.errs {
tmp = append(tmp, err.Error())
}
m := map[string]interface{}{
"kind": e.kind.String(),
"errors": tmp,
}
if len(e.attrs) > 0 {
m["attrs"] = slog.GroupValue(maps.Values(e.attrs)...)
}
return json.Marshal(m)
}

// Errors returns all errors parsed by the error
func (e *ErrorX) Errors() []error {
return e.errs
Expand Down Expand Up @@ -97,18 +112,6 @@ func (e *ErrorX) Is(err error) bool {
return false
}

// MarshalJSON returns the json representation of the error
func (e *ErrorX) MarshalJSON() ([]byte, error) {
m := map[string]interface{}{
"kind": e.kind.String(),
"errors": e.errs,
}
if len(e.attrs) > 0 {
m["attrs"] = slog.GroupValue(maps.Values(e.attrs)...)
}
return json.Marshal(m)
}

// Error returns the error string
func (e *ErrorX) Error() string {
var sb strings.Builder
Expand Down Expand Up @@ -158,7 +161,9 @@ func FromError(err error) *ErrorX {

// New creates a new error with the given message
func New(format string, args ...interface{}) *ErrorX {
return &ErrorX{errs: []error{fmt.Errorf(format, args...)}}
e := &ErrorX{}
e.append(fmt.Errorf(format, args...))
return e
}

// Msgf adds a message to the error
Expand Down
9 changes: 9 additions & 0 deletions errkit/errors_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package errkit

import (
"encoding/json"
"testing"

"github.com/pkg/errors"
Expand Down Expand Up @@ -105,3 +106,11 @@ func TestErrKindCheck(t *testing.T) {
require.True(t, errx.kind.Is(ErrKindNetworkPermanent), "expected to be able to find the original error")
})
}

func TestMarshalError(t *testing.T) {
x := New("port closed or filtered").SetKind(ErrKindNetworkPermanent)
wrapped := Wrap(x, "this is a wrapped error")
marshalled, err := json.Marshal(wrapped)
require.NoError(t, err, "expected to be able to marshal the error")
require.Equal(t, `{"errors":["port closed or filtered","this is a wrapped error"],"kind":"network-permanent-error"}`, string(marshalled))
}

0 comments on commit c6364a3

Please sign in to comment.