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);
}
};