Skip to content

Commit b92f908

Browse files
committed
Add marshal and unmarshal methods for Error.
This is based off #15, which was never merged due to cla.
1 parent 72917a1 commit b92f908

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

multierror.go

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

33
import (
4+
"encoding/json"
45
"fmt"
56
)
67

@@ -39,6 +40,32 @@ func (e *Error) GoString() string {
3940
return fmt.Sprintf("*%#v", *e)
4041
}
4142

43+
// MarshalJSON returns a valid json representation of a multierror,
44+
// as an object with an array of error strings.
45+
func (e *Error) MarshalJSON() ([]byte, error) {
46+
j := map[string][]string{
47+
"errors": []string{},
48+
}
49+
for _, err := range e.Errors {
50+
j["errors"] = append(j["errors"], err.Error())
51+
}
52+
return json.Marshal(j)
53+
}
54+
55+
// UnmarshalJSON from an array of strings.
56+
func (e *Error) UnmarshalJSON(b []byte) error {
57+
j := make(map[string][]string)
58+
if err := json.Unmarshal(b, &j); err != nil {
59+
return err
60+
}
61+
if j["errors"] != nil {
62+
for _, msg := range j["errors"] {
63+
e.Errors = append(e.Errors, fmt.Errorf(msg))
64+
}
65+
}
66+
return nil
67+
}
68+
4269
// WrappedErrors returns the list of errors that this Error is wrapping.
4370
// It is an implementation of the errwrap.Wrapper interface so that
4471
// multierror.Error can be used with that library.

multierror_test.go

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

33
import (
4+
"encoding/json"
45
"errors"
56
"reflect"
67
"testing"
@@ -44,6 +45,29 @@ func TestErrorError_default(t *testing.T) {
4445
}
4546
}
4647

48+
func TestError_json(t *testing.T) {
49+
errs := []error{
50+
errors.New("foo"),
51+
errors.New("bar"),
52+
}
53+
multi := Error{Errors: errs}
54+
b, err := json.Marshal(&multi)
55+
if err != nil {
56+
t.Fatalf("unexpected error; got %#v", err)
57+
}
58+
j := `{"errors":["foo","bar"]}`
59+
if string(b) != j {
60+
t.Errorf("bad representation; got: %s, want: %s", string(b), j)
61+
}
62+
rebuilt := Error{}
63+
if err = json.Unmarshal(b, &rebuilt); err != nil {
64+
t.Fatalf("unexpected error; go %#v", err)
65+
}
66+
if !reflect.DeepEqual(rebuilt, multi) {
67+
t.Fatalf("mismatched types; got: %v, want: %v", rebuilt, multi)
68+
}
69+
}
70+
4771
func TestErrorErrorOrNil(t *testing.T) {
4872
err := new(Error)
4973
if err.ErrorOrNil() != nil {

0 commit comments

Comments
 (0)