Global Client Error Handling #2036
-
Noob question. How would one go for globally handling client side errors? lets say i want the user to be redirected client side to a specific url on "UNAUTHORIZED" errors globally without specifying it on every mutation or query? maybe its react query and has nothing to do with trpc? |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 19 replies
-
See |
Beta Was this translation helpful? Give feedback.
-
I can't get this to work with tRPC. Can someone possibly provide a concrete example of how this would work with certain status codes being handled globally and certain status codes being handled by individual query onError callbacks please? |
Beta Was this translation helpful? Give feedback.
-
Same here can't trigger global error handler defined in react-query |
Beta Was this translation helpful? Give feedback.
-
Is there a way to do this for the I tried the following but I don't think it works. I can see the mutation throwing the error in console but I can't see the output of onError: export function TrpcProvider({ children }: { children: React.ReactNode }): JSX.Element {
const queryClient = useMemo(
() =>
new QueryClient({
queryCache: new QueryCache({
onError: (error) => {
console.log(error.message);
console.log("Printing error");
},
}),
}),
[]
);
const trpcClient = useMemo(
() =>
trpcQuery.createClient(),
[]
);
return (
<trpcQuery.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</trpcQuery.Provider>
);
}
export const trpcQuery = createTRPCReact<AppRouter>(); |
Beta Was this translation helpful? Give feedback.
-
a simpler solution could be wrapping the fetch function: export const createTrpcClient = () => trpc.createClient({
links: [
httpBatchLink({
url: `${process.env.REACT_APP_API_URL}/trpc`,
async fetch(url, options) {
const response = await fetch(url, {
...options,
credentials: 'include',
});
if (response.status === 401) {
window.dispatchEvent(new Event('UNAUTHORIZED'));
}
return response;
},
}),
],
}); |
Beta Was this translation helpful? Give feedback.
See
https://tanstack.com/query/v4/docs/reference/QueryCache#global-callbacks
https://tkdodo.eu/blog/react-query-error-handling#the-global-callbacks