OnError handler #52
-
returning an error if the validation fails is usually fine, but in some cases (like BadRequest) being able do some extra processing (like err := requests.
URL("api.my-site.com").
OnError(func(origErr error, resp *http.Response) error {
data, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading body: %w", err)
}
log.Errorf("error during request: %v", data)
return origErr
}) I understand this is possible by removing the default validator, and adding a handler that calls the default validator and then does this logging on error, and then returns the default error once logged, similar to: err := requests.
URL("api.my-site.com").
AddValidator(nil).
Handle(func(resp *http.Response) error {
err := requests.DefaultValidator(resp)
if err != nil {
data, readErr := io.ReadAll(resp.Body)
if readErr != nil {
return fmt.Errorf("error reading body: %w", readErr)
}
log.Errorf("error during request: %v", data)
return err
}
<do some other processing, maybe using requests.ToJSON or something>
return nil
}) but it just seems like more boilerplate-y. 🤷 This is sort of a more general handling of #32, and would be useful in cases where the object returned by the API varies based on the status code I'd be happy to take a stab at a PR if this is something you'd be interested in. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 21 replies
-
That’s a really interesting idea. I like having a more general way to handle error JSON than #32. It would let you choose whether to return nil error or not, for example. Let’s make an experimental branch and play with it for a while. |
Beta Was this translation helpful? Give feedback.
-
Okay, #63 is merged. Thanks for all the feedback on this. |
Beta Was this translation helpful? Give feedback.
Okay, #63 is merged. Thanks for all the feedback on this.