oapi-codegen icon indicating copy to clipboard operation
oapi-codegen copied to clipboard

Add a client geneneration option to error on invalid responses

Open SoMuchForSubtlety opened this issue 3 years ago • 3 comments

If the server returns an invalid response (for example status 503 with content type text/html from nginx), it can be helpful if the API client returns an error instead of failing silently. Not having this feature has led to a few nil pointer dereferences for me.

It's disabled by default, and can be enabled with output-options.error-on-invalid: true.

with the option disabled:

switch {
case strings.Contains(rsp.Header.Get("Content-Type"), "json"):
	var dest Error
	if err := json.Unmarshal(bodyBytes, &dest); err != nil {
		return nil, err
	}
	response.JSONDefault = &dest
}

with it enabled:

switch {
case rsp.StatusCode == 204:
	break // No response body
case strings.Contains(rsp.Header.Get("Content-Type"), "json"):
	var dest Error
	if err := json.Unmarshal(bodyBytes, &dest); err != nil {
		return nil, err
	}
	response.JSONDefault = &dest
default:
	return response, errors.New("server returned invalid response")
}

Maybe we could use a const error, so errors.Is(err, api.ErrInvalidResponse) can be used.

SoMuchForSubtlety avatar May 27 '22 19:05 SoMuchForSubtlety

I like this :)

I also do work extensively with the generated client.

Could you update the README.md in this pull request

Edit:

server returned an unexpected response

jxsl13 avatar May 30 '22 14:05 jxsl13

Could you update the README.md in this pull request

Individual options are not really addressed in the README, there is just a reference to the go struct where they are defined. Should I add a section that describes all possible parameters?

SoMuchForSubtlety avatar Jun 02 '22 13:06 SoMuchForSubtlety

Any chance for a review by a maintainer? 🙂

SoMuchForSubtlety avatar Aug 10 '22 10:08 SoMuchForSubtlety

@maintainer pls review

erendogan51 avatar Oct 17 '22 13:10 erendogan51