Skip to content
This repository has been archived by the owner on Jan 2, 2022. It is now read-only.

Commit

Permalink
New: add a custom error type for auth errors
Browse files Browse the repository at this point in the history
  • Loading branch information
billglover committed Jun 23, 2018
1 parent 8bf27dc commit b8e4a99
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
6 changes: 6 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*htt
// of the standard response. Others respond with a standardised error structure.
if c := resp.StatusCode; c >= 300 {

// Handle auth errors
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
err := AuthError(http.StatusText(resp.StatusCode))
return resp, err
}

// Try parsing the response using the standard error schema. If this fails we wrap the parsing
// error and return. Otherwise return the errors included in the API response payload.
var e = Errors{}
Expand Down
24 changes: 24 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,30 @@ func TestDo(t *testing.T) {
tc.Error("should not return a response", cross)
}
})

t.Run("GET request that returns a forbidden response", func(tc *testing.T) {
client, mux, _, teardown := setup()
defer teardown()

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
checkMethod(tc, r, http.MethodGet)
w.WriteHeader(http.StatusForbidden)
})

req, _ := client.NewRequest("GET", ".", nil)
resp, err := client.Do(context.Background(), req, nil)

checkStatus(tc, resp, http.StatusForbidden)
checkHasError(tc, err)
if _, ok := err.(AuthError); ok == false {
t.Errorf("should return a starling.AuthError: %T", err)
}
if err, ok := err.(Error); ok == true && err.Temporary() == true {
t.Errorf("should not return a temporary error")
}

})

}

// Setup establishes a test Server that can be used to provide mock responses during testing.
Expand Down
15 changes: 15 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package starling

// Error specifies additional methods on the standard error interface
type Error interface {
error
Temporary() bool
}

// AuthError indicates an issue with the authentication token
type AuthError string

func (e AuthError) Error() string { return string(e) }

// Temporary indicates if an error is temporary
func (e AuthError) Temporary() bool { return false }

0 comments on commit b8e4a99

Please sign in to comment.