Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow marshalling a multi-error #15

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions multierror.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package multierror

import (
"encoding/json"
"errors"
"fmt"
)

Expand All @@ -20,6 +22,34 @@ func (e *Error) Error() string {
return fn(e.Errors)
}

// MarshalJSON returns a valid json representation of a multierror,
// as an object with an array of error strings.
func (e *Error) MarshalJSON() ([]byte, error) {
j := map[string][]string{
"errors": []string{},
}
for _, err := range e.Errors {
j["errors"] = append(j["errors"], err.Error())
}

return json.Marshal(j)
}

// UnmarshalJSON parses the output of Marshal json.
func (e *Error) UnmarshalJSON(b []byte) error {
j := make(map[string][]string)
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
if _, ok := j["errors"]; ok {
for _, msg := range j["errors"] {
e.Errors = append(e.Errors, errors.New(msg))
}
}
return nil
}

// ErrorOrNil returns an error interface if this Error represents
// a list of errors, or returns nil if the list of errors is empty. This
// function is useful at the end of accumulation to make sure that the value
Expand Down
31 changes: 31 additions & 0 deletions multierror_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package multierror

import (
"encoding/json"
"errors"
"reflect"
"testing"
Expand Down Expand Up @@ -68,3 +69,33 @@ func TestErrorWrappedErrors(t *testing.T) {
t.Fatalf("bad: %s", multi.WrappedErrors())
}
}

func TestErrorJson(t *testing.T) {
errors := []error{
errors.New("foo"),
errors.New("bar"),
}

multi := &Error{Errors: errors}

b, err := json.Marshal(multi)
if err != nil {
t.Fatalf("bad: %#v", err)
}

actual := `{"errors":["foo","bar"]}`

if string(b) != actual {
t.Fatalf("bad: %#v != %#v", string(b), actual)
}

rebuilt := &Error{}
err = json.Unmarshal(b, &rebuilt)
if err != nil {
t.Fatalf("bad: %#v", err)
}

if !reflect.DeepEqual(rebuilt, multi) {
t.Fatalf("bad: %#v != %#v", rebuilt, multi)
}
}