add error helpers

This commit is contained in:
Ryan Cavicchioni 2020-04-05 18:54:40 -05:00
parent 7fd366823f
commit e373e7e273
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D
2 changed files with 19 additions and 25 deletions

View File

@ -114,6 +114,20 @@ func NewResponse(r *http.Response) (*Response, error) {
return &resp, nil
}
func (r *Response) IsError() bool {
return r.StatusCode > 299
}
func (r *Response) GetLifxError() (err error) {
var (
s *LifxResponse
)
if err = json.NewDecoder(r.Body).Decode(&s); err != nil {
return nil
}
return errors.New(s.Error)
}
func (c *Client) NewRequest(method, url string, body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest(method, url, body)
if err != nil {

View File

@ -3,7 +3,6 @@ package lifx
import (
//"crypto/tls"
"encoding/json"
"errors"
"net/http"
"time"
)
@ -89,25 +88,6 @@ type (
}
)
func NewApiError(resp *Response) error {
var (
s *LifxResponse
err error
)
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
return err
}
return errors.New(s.Error)
}
func IsApiError(resp *Response) bool {
return resp.StatusCode > 299
}
func (s Status) Success() bool {
return s == OK
}
func (c *Client) SetState(selector string, state State) (*LifxResponse, error) {
var (
err error
@ -120,8 +100,8 @@ func (c *Client) SetState(selector string, state State) (*LifxResponse, error) {
}
defer resp.Body.Close()
if IsApiError(resp) {
return nil, NewApiError(resp)
if resp.IsError() {
return nil, resp.GetLifxError()
}
if state.Fast && resp.StatusCode == http.StatusAccepted {
@ -190,8 +170,8 @@ func (c *Client) Toggle(selector string, duration float64) (*LifxResponse, error
}
defer resp.Body.Close()
if IsApiError(resp) {
return nil, NewApiError(resp)
if resp.IsError() {
return nil, resp.GetLifxError()
}
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
@ -214,7 +194,7 @@ func (c *Client) ListLights(selector string) ([]Light, error) {
defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, NewApiError(resp)
return nil, resp.GetLifxError()
}
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {