Skip to content

Commit 34e5573

Browse files
committed
Refactor HandleAPIError function to improve error handling
1 parent 0acea4b commit 34e5573

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

errors/http_error_handling.go

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,11 @@ func (e *APIError) Error() string {
3232
}
3333

3434
// HandleAPIError handles error responses from the API, converting them into a structured error if possible.
35-
func HandleAPIError(resp *http.Response, log logger.Logger) error {
35+
func HandleAPIError(resp *http.Response, log logger.Logger) *APIError {
3636
var structuredErr StructuredError
3737
err := json.NewDecoder(resp.Body).Decode(&structuredErr)
3838
if err == nil && structuredErr.Error.Message != "" {
39-
// Using structured logging to log the structured error details
39+
// Log the structured error details
4040
log.Warn("API returned structured error",
4141
zap.String("status", resp.Status),
4242
zap.String("error_code", structuredErr.Error.Code),
@@ -49,22 +49,12 @@ func HandleAPIError(resp *http.Response, log logger.Logger) error {
4949
}
5050
}
5151

52-
var errMsg string
53-
err = json.NewDecoder(resp.Body).Decode(&errMsg)
54-
if err != nil || errMsg == "" {
55-
errMsg = fmt.Sprintf("Unexpected error with status code: %d", resp.StatusCode)
56-
// Logging with structured fields
57-
log.Error("Failed to decode API error message, using default error message",
58-
zap.String("status", resp.Status),
59-
zap.String("error_message", errMsg),
60-
)
61-
} else {
62-
// Logging non-structured error as a warning with structured fields
63-
log.Warn("API returned non-structured error",
64-
zap.String("status", resp.Status),
65-
zap.String("error_message", errMsg),
66-
)
67-
}
52+
// Default error message for non-structured responses or decode failures
53+
errMsg := fmt.Sprintf("Unexpected error with status code: %d", resp.StatusCode)
54+
log.Error("Failed to decode API error message, using default error message",
55+
zap.String("status", resp.Status),
56+
zap.String("error_message", errMsg),
57+
)
6858

6959
return &APIError{
7060
StatusCode: resp.StatusCode,

0 commit comments

Comments
 (0)