Skip to content

Commit

Permalink
better error handling in create resources apiclient methods
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasmenendez committed Aug 21, 2024
1 parent c64235e commit 3e2e7c5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
2 changes: 2 additions & 0 deletions apiclient/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ var (
// ErrDecodingResponse is returned when there is an error decoding the response
// from the API. The response is decoded from JSON and this process can fail.
ErrDecodingResponse = fmt.Errorf("error decoding response")
// ErrAlreadyExists is returned when the resource already exists
ErrAlreadyExists = fmt.Errorf("resource already exists")
)
7 changes: 6 additions & 1 deletion apiclient/strategies.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,12 @@ func (c *HTTPclient) CreateStrategy(request *api.Strategy) (uint64, error) {
log.Errorf("error closing response body: %v", err)
}
}()
if res.StatusCode != http.StatusAccepted {
switch res.StatusCode {
case http.StatusAccepted, http.StatusOK:
break
case http.StatusConflict:
return 0, ErrAlreadyExists
default:
return 0, fmt.Errorf("%w: %s", ErrNoStatusOk,
fmt.Errorf("%d %s", res.StatusCode, http.StatusText(res.StatusCode)))
}
Expand Down
8 changes: 6 additions & 2 deletions apiclient/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,14 @@ func (c *HTTPclient) CreateToken(token *api.Token) error {
log.Errorf("error closing response body: %v", err)
}
}()
if res.StatusCode != http.StatusCreated && res.StatusCode != http.StatusOK && res.StatusCode != http.StatusConflict {
switch res.StatusCode {
case http.StatusCreated, http.StatusOK:
return nil
case http.StatusConflict:
return ErrAlreadyExists
default:
return fmt.Errorf("%w: %w", ErrNoStatusOk, fmt.Errorf("%d %s", res.StatusCode, http.StatusText(res.StatusCode)))
}
return nil
}

// DeleteToken method deletes a token in the API, it accepts the tokenID,
Expand Down

0 comments on commit 3e2e7c5

Please sign in to comment.