Compare commits

..

2 Commits

Author SHA1 Message Date
bba7c22460
improve error handling 2020-03-26 20:52:11 -05:00
4d496f7524
formatting 2020-03-26 20:51:26 -05:00
2 changed files with 21 additions and 6 deletions

View File

@ -9,12 +9,7 @@ import (
) )
var ( var (
idWidth int = 0 idWidth, locationWidth, groupWidth, labelWidth, lastSeenWidth, powerWidth int
locationWidth int = 0
groupWidth int = 0
labelWidth int = 0
lastSeenWidth int = 0
powerWidth int = 0
) )
func init() { func init() {

View File

@ -3,6 +3,7 @@ package lifx
import ( import (
//"crypto/tls" //"crypto/tls"
"encoding/json" "encoding/json"
"fmt"
"net/http" "net/http"
"time" "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 { func (s Status) Success() bool {
return s == OK return s == OK
} }
@ -170,6 +182,10 @@ func (c *Client) Toggle(selector string, duration float64) (*Response, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, NewAPIError(resp)
}
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil { if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
return nil, err return nil, err
} }
@ -189,6 +205,10 @@ func (c *Client) ListLights(selector string) ([]Light, error) {
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, NewAPIError(resp)
}
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil { if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
return nil, err return nil, err
} }