From bba7c22460cb323a94b7edf9aaf741ee2e4a45f6 Mon Sep 17 00:00:00 2001 From: Ryan Cavicchioni Date: Thu, 26 Mar 2020 20:52:11 -0500 Subject: [PATCH] improve error handling --- lights.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lights.go b/lights.go index 3d72c76..3b4ade2 100644 --- a/lights.go +++ b/lights.go @@ -3,6 +3,7 @@ package lifx import ( //"crypto/tls" "encoding/json" + "fmt" "net/http" "time" ) @@ -88,6 +89,17 @@ type ( } ) +func NewAPIError(resp *http.Response) error { + var ( + s *Response + err error + ) + if err = json.NewDecoder(resp.Body).Decode(&s); err != nil { + return err + } + return fmt.Errorf("fatal: %s", s.Error) +} + func (s Status) Success() bool { return s == OK } @@ -170,6 +182,10 @@ func (c *Client) Toggle(selector string, duration float64) (*Response, error) { } defer resp.Body.Close() + if resp.StatusCode > 299 { + return nil, NewAPIError(resp) + } + if err = json.NewDecoder(resp.Body).Decode(&s); err != nil { return nil, err } @@ -189,6 +205,10 @@ func (c *Client) ListLights(selector string) ([]Light, error) { } defer resp.Body.Close() + if resp.StatusCode > 299 { + return nil, NewAPIError(resp) + } + if err = json.NewDecoder(resp.Body).Decode(&s); err != nil { return nil, err }