openapi-typescript-fetch icon indicating copy to clipboard operation
openapi-typescript-fetch copied to clipboard

Can't modify message of `ApiError` in middleware

Open wbobeirne opened this issue 3 years ago • 0 comments
trafficstars

I wanted to do some quick handling to set the err.message of ApiErrors to something in my body, so I whipped up a quick middleware that looks like this:

fetcher.use(async (url, init, next) => {
  try {
    return await next(url, init);
  } catch (err) {
    if (err instanceof ApiError && err.data?.message) {
      err.message = err.data.message;
    }
    throw err;
  }
});

However, I found that the error would still use the default message. I noticed that this is because of this bit: https://github.com/ajaishankar/openapi-typescript-fetch/blob/main/src/fetcher.ts#L207-L209. While I can make my own class that wraps errors to work around this, I would lose that nice getActualType typing. Would you be open to changing the ApiError constructor to respect an existing message if one has been set?

If you have a suggestion of a more "correct" way to do this, I'm all ears, but I use err.message as kind of a generic fallback in a lot of places in my code, and I don't want to have to make everything fetcher response body-aware to display better error messages.

wbobeirne avatar May 30 '22 03:05 wbobeirne