From 8de4cfaba08f6e1d7b24e47c711e0d22a638ee9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20T=C3=B6lle?= Date: Tue, 19 Sep 2023 15:10:07 +0200 Subject: [PATCH] feat(error): include http status code in api errors --- hcloud/client.go | 5 ++++- hcloud/client_test.go | 3 +++ hcloud/error.go | 3 +++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/hcloud/client.go b/hcloud/client.go index b2a1190e..66520edc 100644 --- a/hcloud/client.go +++ b/hcloud/client.go @@ -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. diff --git a/hcloud/client_test.go b/hcloud/client_test.go index 36164cb7..6712f0ae 100644 --- a/hcloud/client_test.go +++ b/hcloud/client_test.go @@ -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) { diff --git a/hcloud/error.go b/hcloud/error.go index ac689d11..91647f60 100644 --- a/hcloud/error.go +++ b/hcloud/error.go @@ -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 {