Skip to content

Commit

Permalink
Add handling for error status codes
Browse files Browse the repository at this point in the history
  • Loading branch information
tgrosinger committed Aug 12, 2023
1 parent 26e0bf3 commit 1d6bcea
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
22 changes: 22 additions & 0 deletions message_streams_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,28 @@ func TestListMessageStreams(t *testing.T) {
}
}

func TestGetUnknownMessageStream(t *testing.T) {
responseJSON := `{"ErrorCode":1226,"Message":"The message stream for the provided 'ID' was not found."}`

tMux.HandleFunc(pat.Get("/message-streams/unknown"), func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusUnprocessableEntity)
_, _ = w.Write([]byte(responseJSON))
})

res, err := client.GetMessageStream(context.Background(), "unknown")
if err == nil {
t.Fatalf("MessageStream: expected error")
}
if err.Error() != "The message stream for the provided 'ID' was not found." {
t.Fatalf("MessageStream: wrong error message (%s)", err.Error())
}

var zero MessageStream
if res != zero {
t.Fatalf("MessageStream: expected empty response")
}
}

func TestGetMessageStream(t *testing.T) {
responseJSON := `{
"ID": "broadcasts",
Expand Down
11 changes: 11 additions & 0 deletions postmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,17 @@ func (client *Client) doRequest(ctx context.Context, opts parameters, dst interf
if err != nil {
return
}

if res.StatusCode >= 400 {
// If the status code is not a success, attempt to unmarshall the body into the APIError struct.
var apiErr APIError
err = json.Unmarshal(body, &apiErr)
if err != nil {
return
}
return apiErr
}

err = json.Unmarshal(body, dst)
return
}
Expand Down

0 comments on commit 1d6bcea

Please sign in to comment.