Skip to content

Commit 6f69731

Browse files
author
Steve Moyer
committed
Enhances error handling in resource() (with tests)
1 parent 97b01e9 commit 6f69731

3 files changed

Lines changed: 61 additions & 1 deletion

File tree

pkg/scim/client.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,5 +377,15 @@ func (c Client) resource(resp *http.Response, res Resource) error {
377377
if err != nil {
378378
return err
379379
}
380-
return json.Unmarshal(body, res)
380+
381+
err = json.Unmarshal(body, res)
382+
if err != nil {
383+
return CodecError{
384+
Err: err.Error(),
385+
Op: Unmarshal,
386+
Body: body,
387+
}
388+
}
389+
390+
return nil
381391
}

pkg/scim/client_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,36 @@ func TestResourceOrError(t *testing.T) {
257257
Description: "Bad request",
258258
},
259259
},
260+
{
261+
name: "No body",
262+
mock: httptest.MockTransport{
263+
Req: &http.Request{
264+
Header: map[string][]string{},
265+
},
266+
Resp: &http.Response{
267+
StatusCode: 200,
268+
Body: nil,
269+
},
270+
},
271+
exp: errors.New("<No body>"),
272+
},
273+
{
274+
name: "Bad JSON",
275+
mock: httptest.MockTransport{
276+
Req: &http.Request{
277+
Header: map[string][]string{},
278+
},
279+
Resp: &http.Response{
280+
StatusCode: 200,
281+
Body: ioutil.NopCloser(strings.NewReader("}")),
282+
},
283+
},
284+
exp: CodecError{
285+
Err: "invalid character '}' looking for beginning of value",
286+
Op: Unmarshal,
287+
Body: []byte("}"),
288+
},
289+
},
260290
{
261291
name: "Correct",
262292
mock: httptest.MockTransport{

pkg/scim/codec.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package scim
2+
3+
import "fmt"
4+
5+
type CodecOperation string
6+
7+
const (
8+
Marshal CodecOperation = "Marshal"
9+
Unmarshal CodecOperation = "Unmarshal"
10+
)
11+
12+
type CodecError struct {
13+
Err string
14+
Op CodecOperation
15+
Body []byte
16+
}
17+
18+
func (ce CodecError) Error() string {
19+
return fmt.Sprintf("Err: %s, Operation: %s, Body: %s", ce.Err, ce.Op, string(ce.Body))
20+
}

0 commit comments

Comments
 (0)