Search code examples
goopenapi-generator

How do I get access to HTTP error body using a OpenAPI Generator Client SDK


OpenAPI Generator creates API functions that follow the general pattern:

func (api *MyAPI) OperationId(context.Context) (ResponseStruct, *http.Response, error)

How can I retrieve the HTTP body on an error? When the HTTP Status Code is an error, error is not nil, however, it does not include the body and neither does *http.Response as the body has been read already. And, the error is not unmarshaled into the ResponseStruct as the success and failure definitions are different.


Solution

  • The generated client creates a mypackage.GenericOpenAPIError struct which is returned as an error, where mypackage is the package name of the client. It stores the HTTP error body in the GenericOpenAPIError.body property which can be accessed by the Body() []byte function. However, because function definition returns an error which does not support the Body() function the error needs to be cast before you can access it.

    Here's the code that creates the error from a generated client:

    if localVarHttpResponse.StatusCode >= 300 {
        newErr := GenericOpenAPIError{
            body:  localVarBody,
            error: localVarHttpResponse.Status,
        }
    

    To access the body property, casting the error is needed. For example:

    data, resp, err := myclient.MyAPI.OperationId(context.Background())
    if err != nil && resp.StatusCode >= 300 {
        openAPIErr := err.(mypackage.GenericOpenAPIError)
        fmt.Println(string(openAPIErr.Body()))
    }
    

    Since this needs to be decoded into a struct in the generated client package, it would be useful to add this as a helper function in the client package.