Skip to content

Commit

Permalink
Add marshal and unmarshal methods for Error.
Browse files Browse the repository at this point in the history
This is based off hashicorp#15, which was never merged due to cla.
  • Loading branch information
theherk committed Dec 30, 2019
1 parent 72917a1 commit b92f908
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
27 changes: 27 additions & 0 deletions multierror.go
@@ -1,6 +1,7 @@
package multierror

import (
"encoding/json"
"fmt"
)

Expand Down Expand Up @@ -39,6 +40,32 @@ 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 := map[string][]string{
"errors": []string{},
}
for _, err := range e.Errors {
j["errors"] = append(j["errors"], err.Error())
}
return json.Marshal(j)
}

// UnmarshalJSON from an array of strings.
func (e *Error) UnmarshalJSON(b []byte) error {
j := make(map[string][]string)
if err := json.Unmarshal(b, &j); err != nil {
return err
}
if j["errors"] != nil {
for _, msg := range j["errors"] {
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
@@ -1,6 +1,7 @@
package multierror

import (
"encoding/json"
"errors"
"reflect"
"testing"
Expand Down Expand Up @@ -44,6 +45,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 := `{"errors":["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

0 comments on commit b92f908

Please sign in to comment.