-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
Problem statement
Seeking guidance. Say various responses are modelled by the swagger spec (see below) and there are many such endpoints and all I want do to is to categorise them by server errors or client errors. The HTTP spec makes this easy: server errors have status codes 500-599; and client errors have status codes 400-499. The generated response structs (e.g. GetBadRequest, GetTooManyRequests, GetInternalServerError, etc.) hide or obfuscate the HTTP status code and I am reduced to using a priori knowledge to compute the distinction. E.g.
func IsClientError(err error) bool {
switch err := p.cause.(type) {
case
*operations.GetBadRequest,
*operations.GetTooManyRequests,
*operations.PostBadRequest,
*operations.PostTooManyRequests,
*operations.EtcBadRequest,
*operations.EtcTooManyRequests:
return true
case *runtime.APIError:
return err.Code >= 400 && err.Code < 500
}
return false
}
I'm aware that APIError has a Code field. But what I'm seeking is a common interface across all HTTP error values that might be produced by generated client operation interfaces. E.g.
type HTTPResponse interface {
StatusMessage() string
StatusCode() int
}
I realise this may be a can of worms... but it's very difficult to maintain functions such as the above IsClientError. I wasn't able to find anything that converts, say, *operations.GetBadRequest to *runtime.APIError. I do see that a const is generated:
// GetBadRequestCode is the HTTP code returned for type GetBadRequest
const GetBadRequestCode int = 400
But I don't see how that improves the situation.
Is this a common scenario? Am I missing a trick?
Swagger specification
paths:
/:
get:
operationId: Get
responses:
'200':
description: OK
'400':
description: Bad Request
'429':
description: Too Many Requests
'500':
description: Internal Server Error
Environment
swagger version: v0.25.0
go version: 1.17.5