-
At the moment the only way to return the 4XX body response is to handle the response which defeats the purpose of using the library. I would like to know whether there is an option to get the response body of error codes |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
So I think the actual // CheckStatus validates the response has an acceptable status code.
func CheckStatus(acceptStatuses ...int) requests.ResponseHandler {
return func(res *http.Response) error {
for _, code := range acceptStatuses {
if res.StatusCode == code {
return nil
}
}
// cast error into error response
se := (*requests.ResponseError)(res)
// read the error response body
var buf strings.Builder
_, copyErr := io.Copy(&buf, se.Body)
if copyErr == nil {
return errors.New(buf.String())
}
return copyErr
}
} |
Beta Was this translation helpful? Give feedback.
-
There's no method for getting the body of a response with a bad status, but you can build your own by combining the existing validators/handlers: var errorBody string
myStatusChecker := func(res *http.Response) error {
err := requests.CheckStatus(200)(res)
if requests.HasStatusErr(err, 400) {
if copyErr := requests.ToString(&errorBody)(res); copyErr != nil {
return copyErr
}
}
return err
}
err := requests.
URL(url).
AddValidator(myStatusChecker).
Fetch(ctx) |
Beta Was this translation helpful? Give feedback.
-
The ValidatorHandler added in v0.23.1 lets you run a fallback handler when a validator fails. The example copies the body to a string when the statuscheck fails. See https://pkg.go.dev/github.com/carlmjohnson/requests#example-ValidatorHandler err := requests.
URL("http://example.com/404").
ToString(®ularBody).
AddValidator(
requests.ValidatorHandler(
requests.DefaultValidator,
requests.ToString(&errBody),
)).
Fetch(context.Background()) |
Beta Was this translation helpful? Give feedback.
So I think the actual
CheckStatus
should be something like this: