Skip to content

Commit 704a344

Browse files
committed
Wrap JSON decoding error in ErrJSONDecode to allow the caller an opportunity to inspect the payload received from AT
1 parent 278f415 commit 704a344

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

sms/sms.go

+34-1
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,30 @@ package sms
22

33
import (
44
"encoding/json"
5+
"io"
6+
"io/ioutil"
57
"strings"
68

79
"github.com/kingzbauer/africastalking-go/client"
810
)
911

12+
// ErrJSONDecode thrown when an error is encountered when decoding a payload
13+
// Include the payload
14+
type ErrJSONDecode struct {
15+
parent error
16+
Payload []byte
17+
}
18+
19+
// Error implements the error interface
20+
func (err ErrJSONDecode) Error() string {
21+
return err.parent.Error()
22+
}
23+
24+
// Unwrap for compatibility with errors.Unwrap method
25+
func (err ErrJSONDecode) Unwrap() error {
26+
return err.parent
27+
}
28+
1029
// NewRequest creates a new request object with the minimal required fields.
1130
// You can leave `from` as empty string, defaults to AFRICASTKNG
1231
func NewRequest(message string, to []string, from string) *Request {
@@ -25,7 +44,21 @@ func SendMessage(cli *client.Client, req *Request) (rep *Response, err error) {
2544
}
2645

2746
rep = &Response{}
28-
if err := json.NewDecoder(repBody).Decode(rep); err != nil {
47+
bodyContent, err := ioutil.ReadAll(repBody)
48+
if err != nil {
49+
return nil, err
50+
}
51+
// Close the body if is supports it
52+
if closer, ok := repBody.(io.Closer); ok {
53+
closer.Close()
54+
}
55+
56+
if err := json.Unmarshal(bodyContent, rep); err != nil {
57+
// Use ErrJSONDecode to provide the caller with the opportunity to inspect the payload
58+
err = &ErrJSONDecode{
59+
parent: err,
60+
Payload: bodyContent,
61+
}
2962
return nil, err
3063
}
3164

0 commit comments

Comments
 (0)