Skip to content

Commit

Permalink
return custom error from authz roundtripper
Browse files Browse the repository at this point in the history
  • Loading branch information
joshi4 committed Jan 15, 2025
1 parent a1f0e1c commit 35163f1
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
15 changes: 10 additions & 5 deletions authz/roundtripper.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 6,20 @@ import (
"net/http"
)

var ErrInvalidClient = errors.New("invalid client")
var ErrInvalidAuthzClient = errors.New("invalid authz client")

type AuthorizedRoundTripper struct {
token string
savvyVersion string
// wrap error returned by RoundTrip
wrapErr error
}

func NewRoundTripper(token, savvyVersion string) *AuthorizedRoundTripper {
return &AuthorizedRoundTripper{token: token, savvyVersion: savvyVersion}
// NewRoundTripper returns a new AuthorizedRoundTripper
//
// Caller must provide non nil err to wrap the error returned by RoundTrip
func NewRoundTripper(token, savvyVersion string, err error) *AuthorizedRoundTripper {
return &AuthorizedRoundTripper{token: token, savvyVersion: savvyVersion, wrapErr: err}
}

func (a *AuthorizedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
Expand All @@ -26,14 31,14 @@ func (a *AuthorizedRoundTripper) RoundTrip(req *http.Request) (*http.Response, e
// Use the embedded Transport to perform the actual request
res, err := http.DefaultTransport.RoundTrip(clonedReq)
if err != nil {
err = fmt.Errorf("%w: %v", ErrInvalidClient, err)
err = fmt.Errorf("%w: %v", a.wrapErr, err)
return nil, err
}

// If we get a 401 Unauthorized, then the token is expired
// and we need to refresh it
if res.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("%w: invalid token", ErrInvalidClient)
return nil, fmt.Errorf("%w: invalid token", a.wrapErr)
}
return res, err
}
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 89,7 @@ func New() (Client, error) {
}

cl := &http.Client{
Transport: authz.NewRoundTripper(cfg.Token, config.Version()),
Transport: authz.NewRoundTripper(cfg.Token, config.Version(), ErrInvalidClient),
}

c := &client{
Expand Down

0 comments on commit 35163f1

Please sign in to comment.