I have an app that using open api yaml + axios. I create an customInstance for API call, the function is :
export const customInstance = async <T>(
config: AxiosRequestConfig
): Promise<T> => {
const source = axios.CancelToken.source();
const token = await SecureStore.getItemAsync('token');
const promise = AXIOS_INSTANCE({
...config,
cancelToken: source.token,
headers: {
Authorization: `Bearer ${token || ''}`,
},
})
.then(({ data }) => data)
.catch(async (e: AxiosError) => {
if (e?.response?.status === 401) {
// token expired
await SecureStore.deleteItemAsync('token');
throw Error('ERR-401');
}
throw {
message: e.message,
status: e?.response?.status,
data: e?.response?.data,
};
});
// @ts-ignore
promise.cancel = () => {
source.cancel('Query was cancelled by SWR');
};
return promise;
};
You can see I try to return a customized error message for redirect user to login page when token is expired, and I add my error boundary into rootLayout
, the error boundary is from expo router, the custom error boundary is :
export function ErrorBoundary({ error, retry }: ErrorBoundaryProps) {
if (error.message === 'ERR-401') {
// Unauthorized
return <Redirect href="/" />;
}
return (
<View style={{ flex: 1 }}>
<SafeAreaView style={{ justifyContent: 'center', alignItems: 'center' }}>
<Text>{error.message}</Text>
<Text onPress={retry}>Try Again?</Text>
</SafeAreaView>
</View>
);
}
This has been working previously when I set it up, but after a few iterations, the routing changed. I found out the error now is not caught by the error boundary, instead, there will be a console.log
warning showing up at the bottom
Possible unhandled promise rejection(id:0) Error:ERR-401
I tried to use another error boundary lib, but I have the same result, so I am thinking that maybe this throw Error('ERR-401')
somehow is not recognized as an error and the boundary is not catching it?
Because when I try to throw an error in the component, the ErrorBoundary
is still working.
Is there any possible that this error has been catching by the dev log before the error boundary? If so, how can I solve this?
Thanks!
Maffia999 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.