Skip to content

Commit

Permalink
Generic API Error Handling (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanz0rz authored Apr 17, 2024
1 parent 53d9e02 commit 965b60b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
15 changes: 9 additions & 6 deletions internal/http_executor/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,18 @@ func (c *Client) handleErrorResponse(resp *http.Response) error {
return fmt.Errorf("reading error response body failed: %v", err)
}

var apiError struct {
Message string `json:"message"`
var errorMessageMap map[string]interface{}
err = json.Unmarshal(body, &errorMessageMap)
if err != nil {
return fmt.Errorf("failed to unmarshal error response body: %v", err)
}
if err := json.Unmarshal(body, &apiError); err != nil {
// Fallback to raw body text if the body cannot be parsed as JSON
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, body)

errFormatted, err := json.MarshalIndent(errorMessageMap, "", " ")
if err != nil {
return fmt.Errorf("failed to format error response body: %v", err)
}

return fmt.Errorf("HTTP %d: %s", resp.StatusCode, apiError.Message)
return fmt.Errorf("%s", errFormatted)
}

// addQueryParameters adds the parameters in the struct params as URL query parameters to s.
Expand Down
9 changes: 7 additions & 2 deletions internal/http_executor/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -126,8 +127,12 @@ func TestExecuteRequest_ServerErrorPOST(t *testing.T) {
t.Fatalf("Expected an error, got nil")
}

expectedErrorMessage := "processing response failed: HTTP 500: internal server error"
if err.Error() != expectedErrorMessage {
expectedErrorMessage := `processing response failed: {
"message": "internal server error"
}`

// Remove all whitespace when comparing the errors
if strings.Join(strings.Fields(err.Error()), "") != strings.Join(strings.Fields(expectedErrorMessage), "") {
t.Errorf("Expected error message '%s', got '%s'", expectedErrorMessage, err.Error())
}
}
Expand Down

0 comments on commit 965b60b

Please sign in to comment.