Skip to content

Commit

Permalink
Enhances error handling in resource() (with tests)
Browse files Browse the repository at this point in the history
  • Loading branch information
Steve Moyer committed Mar 31, 2020
1 parent 97b01e9 commit 6f69731
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
12 changes: 11 additions & 1 deletion pkg/scim/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,5 +377,15 @@ func (c Client) resource(resp *http.Response, res Resource) error {
if err != nil {
return err
}
return json.Unmarshal(body, res)

err = json.Unmarshal(body, res)
if err != nil {
return CodecError{
Err: err.Error(),
Op: Unmarshal,
Body: body,
}
}

return nil
}
30 changes: 30 additions & 0 deletions pkg/scim/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,36 @@ func TestResourceOrError(t *testing.T) {
Description: "Bad request",
},
},
{
name: "No body",
mock: httptest.MockTransport{
Req: &http.Request{
Header: map[string][]string{},
},
Resp: &http.Response{
StatusCode: 200,
Body: nil,
},
},
exp: errors.New("<No body>"),
},
{
name: "Bad JSON",
mock: httptest.MockTransport{
Req: &http.Request{
Header: map[string][]string{},
},
Resp: &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(strings.NewReader("}")),
},
},
exp: CodecError{
Err: "invalid character '}' looking for beginning of value",
Op: Unmarshal,
Body: []byte("}"),
},
},
{
name: "Correct",
mock: httptest.MockTransport{
Expand Down
20 changes: 20 additions & 0 deletions pkg/scim/codec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package scim

import "fmt"

type CodecOperation string

const (
Marshal CodecOperation = "Marshal"
Unmarshal CodecOperation = "Unmarshal"
)

type CodecError struct {
Err string
Op CodecOperation
Body []byte
}

func (ce CodecError) Error() string {
return fmt.Sprintf("Err: %s, Operation: %s, Body: %s", ce.Err, ce.Op, string(ce.Body))
}

0 comments on commit 6f69731

Please sign in to comment.