javascripttypescriptopenapiopenapi-generator

openapi generated client throws away request error information


I'm using the OpenAPI Generator and looking at the code generated for my swagger definitions with "typescript-fetch" as my chosen generator I see something weird:

// Code generated to issue requests
protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
    const { url, init } = await this.createFetchParams(context, initOverrides);
    const response = await this.fetchApi(url, init);
    if (response && (response.status >= 200 && response.status < 300)) {
        return response;
    }
    throw new ResponseError(response, 'Response returned an error code');
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error creation
}

now take a look at how the response error is defined:

export class ResponseError extends Error {
    override name: "ResponseError" = "ResponseError";
    constructor(public response: Response, msg?: string) {
        super(msg);
    }
}

i.e. the reponse itself is passed as a constructor argument and then discarded. I don't know if this is the reason but ultimately I get non-informative error messages e.g:

Error: {"response":{},"name":"ResponseError"}

By inspecting my network tab, I see the POST request has the complete required info and everything should be in that response object. But my hands are tied since the response object itself is ultimately not contained in the error.

I might be doing something wrong in the way I'm trying to print out errors from such an api. If so, please let me know.


Solution

  • The ResponseError object contains the RequestStream of any data coming in. This object also contains the support methods for reading the RequestStream, to be able to do so regardless of the input status type, The are the json(), text(), and binary() methods for data reading,

    What you would like to do I believe is,

    new Client().method().then().catch(error => {
        error.response.json().then(errorBody => {...});
    });