Skip to content

Add marshal and unmarshal methods for Error. #25

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

import (
"encoding/json"
"errors"
"fmt"
)
Expand Down Expand Up @@ -40,6 +41,30 @@ func (e *Error) GoString() string {
return fmt.Sprintf("*%#v", *e)
}

// 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 := []string{}
for _, err := range e.Errors {
j = append(j, err.Error())
}
return json.Marshal(j)
}

// UnmarshalJSON from an array of strings.
func (e *Error) UnmarshalJSON(b []byte) error {
j := []string{}
if err := json.Unmarshal(b, &j); err != nil {
return err
}
if j != nil {
for _, msg := range j {
e.Errors = append(e.Errors, fmt.Errorf(msg))
}
}
return nil
}

// WrappedErrors returns the list of errors that this Error is wrapping. It is
// an implementation of the errwrap.Wrapper interface so that multierror.Error
// can be used with that library.
Expand Down
24 changes: 24 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"
"fmt"
"reflect"
Expand Down Expand Up @@ -45,6 +46,29 @@ func TestErrorError_default(t *testing.T) {
}
}

func TestError_json(t *testing.T) {
errs := []error{
errors.New("foo"),
errors.New("bar"),
}
multi := Error{Errors: errs}
b, err := json.Marshal(&multi)
if err != nil {
t.Fatalf("unexpected error; got %#v", err)
}
j := `["foo","bar"]`
if string(b) != j {
t.Errorf("bad representation; got: %s, want: %s", string(b), j)
}
rebuilt := Error{}
if err = json.Unmarshal(b, &rebuilt); err != nil {
t.Fatalf("unexpected error; go %#v", err)
}
if !reflect.DeepEqual(rebuilt, multi) {
t.Fatalf("mismatched types; got: %v, want: %v", rebuilt, multi)
}
}

func TestErrorErrorOrNil(t *testing.T) {
err := new(Error)
if err.ErrorOrNil() != nil {
Expand Down