Skip to content

Commit

Permalink
Wrap JSON decoding error in ErrJSONDecode to allow the caller an oppo…
Browse files Browse the repository at this point in the history
…rtunity to inspect the payload received from AT
  • Loading branch information
kingzbauer committed Feb 26, 2020
1 parent 278f415 commit 704a344
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion sms/sms.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,30 @@ package sms

import (
"encoding/json"
"io"
"io/ioutil"
"strings"

"github.com/kingzbauer/africastalking-go/client"
)

// ErrJSONDecode thrown when an error is encountered when decoding a payload
// Include the payload
type ErrJSONDecode struct {
parent error
Payload []byte
}

// Error implements the error interface
func (err ErrJSONDecode) Error() string {
return err.parent.Error()
}

// Unwrap for compatibility with errors.Unwrap method
func (err ErrJSONDecode) Unwrap() error {
return err.parent
}

// NewRequest creates a new request object with the minimal required fields.
// You can leave `from` as empty string, defaults to AFRICASTKNG
func NewRequest(message string, to []string, from string) *Request {
Expand All @@ -25,7 +44,21 @@ func SendMessage(cli *client.Client, req *Request) (rep *Response, err error) {
}

rep = &Response{}
if err := json.NewDecoder(repBody).Decode(rep); err != nil {
bodyContent, err := ioutil.ReadAll(repBody)
if err != nil {
return nil, err
}
// Close the body if is supports it
if closer, ok := repBody.(io.Closer); ok {
closer.Close()
}

if err := json.Unmarshal(bodyContent, rep); err != nil {
// Use ErrJSONDecode to provide the caller with the opportunity to inspect the payload
err = &ErrJSONDecode{
parent: err,
Payload: bodyContent,
}
return nil, err
}

Expand Down

0 comments on commit 704a344

Please sign in to comment.