Axios intercept error Promise or throw error

Viewed 1735

I want to centralize some error management in an axios interceptor, like this:

    API.instance.interceptors.response.use(
      response => response,
      error => {
        const modifiedError = error;
        let errorMessage =
          t('common:common-front-end-error') || 'Something wrong happened, please, try later';

        if (error.response?.data?.payload) {
          errorMessage = error.response.data.payload;
        }

        modifiedError.message = errorMessage;
        throw modifiedError;
      }
    );

As you can see, I use throw in order to raise an exception. However, all snippets of code I see in regards to interceptors that returns something bad, use a Promise.reject(whatever) at the end of it.

However, if I use Promise.reject my react-query does not work as I do not use promises. I use await and try/catch. Is there a way to have an interceptor that allows both uses, Promises and await syntax?

This is my react-query snippet:


const fetchBlabla = currentPage => async (): Promise<Blabla> => {
  try {
    const api = API.getInstance();
    const response = await api.get<Blabla>(
      `/api/blabla&limit=20&offset=${(currentPage - 1) * 20}`
    );
    return response.data;
  } catch (err) {
    throw new Error(err.message);
  }
};
1 Answers

async / await is mostly just syntactic sugar for Promises. One defining trait of async functions is that they always must return a Promise, which is why thrown Errors will be transformed into rejected Promises.

So really, there shouldn't be any difference between throwing inside an async function or returning Promise.reject.

Also:

  } catch (err) {
    throw new Error(err.message);
  }

this code does nothing. You catch an error and throw a new Error.

the query function could just as well be:

const fetchBlabla = currentPage => async (): Promise<Blabla> => {
  const api = API.getInstance();
  const response = await api.get<Blabla>(
    `/api/blabla&limit=20&offset=${(currentPage - 1) * 20}`
  );
  return response.data;
};

I have covered a lot of this here

Related