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

typescript fetcher error handler always returns error status "unknown"

Open SeanCondon opened this issue 3 years ago • 1 comments
trafficstars

I cannot see how the code in the fetcher is supposed to pass on any error it gets in the response.

In https://github.com/fabien0102/openapi-codegen/blob/13ca9b35ab0bbd363946baf4a015b3e6d317f728/plugins/typescript/src/templates/fetcher.ts

we have

  try {
...
    if (!response.ok) {
      let error: ErrorWrapper<TError>;
      try {
        error = await response.json();
      } catch (e) {
        error = {
          status: "unknown" as const,
          payload:
            e instanceof Error
              ? \`Unexpected error (\${e.message})\`
              : "Unexpected error"
        };
      }
      throw error;
    }
    if (response.headers.get('content-type')?.includes('json')) {
      return await response.json();
    } else {
      // if it is not a json response, assume it is a blob and cast it to TData
      return (await response.blob()) as unknown as TData;
    }
  } catch (e) {
    throw {
      status: "unknown" as const,
      payload:
        e instanceof Error
          ? \`Network error (\${e.message})\`
          : "Network error"
    }
  }
}

but because the inner throw error is itself inside a try...catch - the outer catch will always catch it, and because it is not an instance of Error it will always give just

{
  "status": "unnown",
  "payload": "Network error"
}

which is not very useful.

I would suggest to dispense with the outer try...catch and use something simpler like:

  if (!response.ok) {
    let error: ErrorWrapper<TError>;
    try {
      error = {
        status: response.status,
        payload: await response.json(),
      } as TError;
    } catch (e) {
      error = {
        status: "unknown" as const,
        payload:
          e instanceof Error
            ? `Unexpected error (${e.message})`
            : "Unexpected error",
      };
    }
    throw error;
  }

SeanCondon avatar Oct 23 '22 19:10 SeanCondon

looks fine to me. Can you open a PR?

needim avatar Nov 10 '22 16:11 needim