Skip to content

Commit

Permalink
Add helper to RequestError for unmarshaling error info to structs
Browse files Browse the repository at this point in the history
  • Loading branch information
achilleasa committed Apr 4, 2019
1 parent d8af3b6 commit 38b5cb5
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
23 changes: 23 additions & 0 deletions rpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
package rpc

import (
"encoding/json"
"reflect"
"strings"

"github.com/juju/errors"
Expand Down Expand Up @@ -42,6 +44,27 @@ func (e *RequestError) ErrorCode() string {
return e.Code
}

// UnmarshalInfo attempts to unmarshal the information contained in the Info
// field of a RequestError into an object instance a pointer to which is passed
// via the to argument. The method will return an error if a non-pointer arg
// is provided.
func (e *RequestError) UnmarshalInfo(to interface{}) error {
if reflect.ValueOf(to).Kind() != reflect.Ptr {
return errors.New("UnmarshalInfo expects a pointer as an argument")
}

data, err := json.Marshal(e.Info)
if err != nil {
return errors.Annotate(err, "could not marshal error information")
}
err = json.Unmarshal(data, to)
if err != nil {
return errors.Annotate(err, "could not unmarshal error information to provided target")
}

return nil
}

func (conn *Conn) send(call *Call) {
conn.sending.Lock()
defer conn.sending.Unlock()
Expand Down
54 changes: 54 additions & 0 deletions rpc/rpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,60 @@ func (s *rpcSuite) TestRecorderErrorPreventsRequest(c *gc.C) {
c.Assert(root.calls, gc.HasLen, 0)
}

func (s *rpcSuite) TestRequestErrorInfoUnmarshaling(c *gc.C) {
type nestedStruct struct {
Baz bool
}
type someStruct struct {
Foo string
Nested nestedStruct
}

specs := []struct {
descr string
info map[string]interface{}
to interface{}
exp interface{}
err string
}{
{
descr: "unmarshal to struct",
info: map[string]interface{}{
"Foo": "bar",
"Nested": map[string]interface{}{
"Baz": true,
},
},
to: new(someStruct),
exp: &someStruct{
Foo: "bar",
Nested: nestedStruct{Baz: true},
},
},
{
descr: "unmarshal to non-pointer",
info: map[string]interface{}{"Foo": "bar"},
to: 42,
err: "UnmarshalInfo expects a pointer as an argument",
},
}

for specIndex, spec := range specs {
c.Logf("test %d: %s", specIndex, spec.descr)

re := &rpc.RequestError{
Info: spec.info,
}
err := re.UnmarshalInfo(spec.to)
if spec.err == "" {
c.Assert(err, gc.IsNil)
c.Assert(spec.to, gc.DeepEquals, spec.exp)
} else {
c.Assert(err, gc.ErrorMatches, spec.err)
}
}
}

func chanReadError(c *gc.C, ch <-chan error, what string) error {
select {
case e := <-ch:
Expand Down

0 comments on commit 38b5cb5

Please sign in to comment.