Advanced Error Handling in React Queries: Retrieving Server Error Codes Alongside isError Conditions #6490
Unanswered
ajaymahadeven
asked this question in
Ideas
Replies: 1 comment 4 replies
-
This can easily be achieved by having a wrapper around the import { QueryKey, UseQueryOptions, useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
export const MyErrorCodes = {
SomethingWentWrong: 10001,
SomethingElseWentWrong: 10002,
} as const;
export class MyError extends Error {
code: number;
constructor(message: string, code: number) {
super(message);
this.code = code;
}
}
export function useQueryWrapper<
TQueryFnData = unknown,
TError = Error,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>) {
const useQueryResult = useQuery<TQueryFnData, TError, TData, TQueryKey>(options);
const errorCode = useMemo(() => {
// If queryFn throws an error of type MyError, you will be able to access the code property
if (useQueryResult.error !== null && useQueryResult.error instanceof MyError) {
return useQueryResult.error.code;
}
return undefined;
}, [useQueryResult.error]);
return {
...useQueryResult,
errorCode,
};
}
// Then you can use it like this:
const { errorCode } = useQueryWrapper({
queryKey: ['myQuery'],
queryFn: async () => {
const res = await fetch('...');
if (!res.ok) {
throw new MyError('Something went wrong', MyErrorCodes.SomethingWentWrong);
}
return res.json();
},
}); |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am exploring the possibility of enhancing error handling in React queries and would like to know if there's a method to not only determine if an error has occurred (as indicated by isError returning a boolean value) but also to retrieve the specific error code returned by the server. This additional detail would enable more precise logic based on both the status code and the isError condition.
For instance, in a scenario where I am working with a component that fetches data from a server, I would like to implement logic where the initial page is saved as a draft in case the server returns a 404 error (indicating the page ID was not found) combined with an isError type of undefined. Essentially, this would allow for different actions depending on whether the page exists or not when the component is rendered. Any guidance on methods or approaches to achieve this would be greatly appreciated.
Beta Was this translation helpful? Give feedback.
All reactions