-
Notifications
You must be signed in to change notification settings - Fork 38
Description
For instance,
if err != nil {
return nil, fmt.Errorf("error building request: %w", err)
}
resp, err := utils.SendRequest(req)
if err != nil {
return nil, fmt.Errorf("error sending request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("received non-2xx status code: %d", resp.StatusCode)
}
updatedResp, err := utils.HandleResponse(resp)
if err != nil {
r
This could be much clearer.
You can:
-
Provide Context with Errors: When wrapping errors, include contextual information to make them more informative. For example, instead of just returning fmt.Errorf("error building request: %w", err), consider including details like the request URL or method.
return nil, fmt.Errorf("error building request: %w", err)
-
Check Response Body for Error Details: In addition to checking the status code, read and parse the response body to get more details about the error. This can provide insights into what went wrong on the server side. Maybe use a switch case example using the http library to help with error codes. (Another suggestion is to create custom error responses in errors.go and make them return so that it's far more clearer and separated.)
switch resp.StatusCode {
case http.StatusOK:
// Process the response body as needed
fmt.Println("Request was successful!")
// Read and process resp.Body
case http.StatusNotFound:
fmt.Println("Resource not found.")
case http.StatusInternalServerError:
fmt.Println("Server error occurred.")
default:
if resp.StatusCode >= 400 {
fmt.Printf("Request failed with status: %d\n", resp.StatusCode)
} else {
fmt.Printf("Received unexpected status: %d\n", resp.StatusCode)
}
}
-
Custom Error Types: Define custom error types for different kinds of errors that your client might encounter. This allows for more precise error handling and can make the code more readable and maintainable.
-
Consistent Error Handling: Ensure that error handling is consistent across all methods in the client. This includes how errors are wrapped, logged, and returned to the caller.
-
Graceful Degradation in Streaming Responses: For streaming responses, implement mechanisms to handle partial data gracefully. This could involve buffering data, handling connection drops, and providing ways to resume or restart the stream if necessary.