Home > OS >  React Query get error status code in global onError handler
React Query get error status code in global onError handler

Time:11-11

When creating the queryClient I want to create a global onError handler that refreshes my access token when the error response code is 401. But I don't know how the status code is accessible on the returned error in the onError handler.

Below is my global onError handler and I only need to access the response code in the if statement to refresh my token at the appropriate time.

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: async (error, query) => {
      // How to get status code fo error
      if (error.status === 401) {
        console.log("Refreshing Token");
        await api.get("/api/refresh-token");
        queryClient.refetchQueries(query.queryKey);
      }
    },
  }),
});

CodePudding user response:

The error is just whatever the rejected Promise has created, so it depends on how you do the actual data fetching.

If it's axios, it will likely be an AxiosError, so the status code should be available there.

If it's fetch, then it depends on how you transform your erroneous status code to a failed Promise, because fetch doesn't do that per default. If it's just:

if (!response.ok) {
  throw new Error("no ok")
}

then you don't have information about the status code at all, because you've not included it in the Error.

All in all, this is out of react-queries hands, because it is agnostic about how data fetching is done.

CodePudding user response:

You should get it by using error.request.status.

const queryClient = new QueryClient({
  queryCache: new QueryCache({
    onError: async (error, query) => {
      // How to get status code fo error
      if (error.request.status === 401) {
        console.log("Refreshing Token");
        await api.get("/api/refresh-token");
        queryClient.refetchQueries(query.queryKey);
      }
    },
  }),
});
  • Related