Skip to content

Commit

Permalink
feat(error): include http status code in api errors
Browse files Browse the repository at this point in the history
  • Loading branch information
apricote committed Sep 19, 2023
1 parent 7ddb2ec commit 8de4cfa
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 1 deletion.
5 changes: 4 additions & 1 deletion hcloud/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,10 @@ func errorFromResponse(resp *http.Response, body []byte) error {
if respBody.Error.Code == "" && respBody.Error.Message == "" {
return nil
}
return ErrorFromSchema(respBody.Error)

hcErr := ErrorFromSchema(respBody.Error)
hcErr.HTTPStatusCode = resp.StatusCode
return hcErr
}

// Response represents a response from the API. It embeds http.Response.
Expand Down
3 changes: 3 additions & 0 deletions hcloud/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ func TestClientError(t *testing.T) {
if apiError.Message != "An error occurred" {
t.Errorf("unexpected error message: %q", apiError.Message)
}
if apiError.HTTPStatusCode != http.StatusUnprocessableEntity {
t.Errorf("unexpected http status code: %q", apiError.HTTPStatusCode)
}
}

func TestClientInvalidToken(t *testing.T) {
Expand Down
3 changes: 3 additions & 0 deletions hcloud/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ type Error struct {
Code ErrorCode
Message string
Details interface{}
// HTTPStatusCode is the status code of the response that included the error.
// It can be converted to a user readable string using net/http.StatusText().
HTTPStatusCode int
}

func (e Error) Error() string {
Expand Down

0 comments on commit 8de4cfa

Please sign in to comment.