Stop react query from retry on 404

TLDR: I cannot get correct typing for the error, as the react query uses unknown type for the error in retry function. They also reccomend to perform a runtime check for the error. I'm kinda stuck as I don't lnow how to retrieve the error code from the error in retry function. --- Currently I'm trying to stop react query client (that's used by the tRPC internally) from retrying on 404 and 401 HTTP errors. I found this issue https://github.com/TanStack/query/discussions/372#discussioncomment-6023276 and adapted the answer to my needs:
const MAX_QUERY_RETRIES = 4;
const SKIPPED_HTTP_CODES = [401, 402, 403, 404];

export const reactQueryRetry = (failureCount: number, error: unknown) => {
if (failureCount > MAX_QUERY_RETRIES) {
return false;
}

if (
error instanceof TRPCError &&
SKIPPED_HTTP_CODES.includes(getHTTPStatusCodeFromError(trpcError))
) {
return false;
}

return true;
};
const MAX_QUERY_RETRIES = 4;
const SKIPPED_HTTP_CODES = [401, 402, 403, 404];

export const reactQueryRetry = (failureCount: number, error: unknown) => {
if (failureCount > MAX_QUERY_RETRIES) {
return false;
}

if (
error instanceof TRPCError &&
SKIPPED_HTTP_CODES.includes(getHTTPStatusCodeFromError(trpcError))
) {
return false;
}

return true;
};
However, after inspecting this further the error isn't an isntance of TRPCError, as its shape differs from the TRPC's error structure:
// https://trpc.io/docs/server/error-handling
const error: TRPCError = {
name: 'TRPCError',
code: 'BAD_REQUEST',
message: '"password" must be at least 4 characters',
};
// https://trpc.io/docs/server/error-handling
const error: TRPCError = {
name: 'TRPCError',
code: 'BAD_REQUEST',
message: '"password" must be at least 4 characters',
};
Error's shape:
{
"meta":{
"response":{}
},
"shape":{
"message":"Quiz not found",
"code":-32004,
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
}
},
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
},
"name":"TRPCClientError"
}
{
"meta":{
"response":{}
},
"shape":{
"message":"Quiz not found",
"code":-32004,
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
}
},
"data":{
"code":"NOT_FOUND",
"httpStatus":404,
"stack":"removed",
"path":"quiz.byId",
"zodError":null
},
"name":"TRPCClientError"
}
So I tried tRPC helpers const trpcError = getTRPCErrorFromUnknown(error) and then getHTTPStatusCodeFromError(trpcError) but the HTTP code returned by helper is 500 instead of 404 visible in JSON.
1 Reply
Kuba
Kuba11mo ago
Alright, the typing was described right in the tRPC docs: https://trpc.io/docs/client/vanilla/infer-types Sometimes you just have to write down the issue and read it step by step to find a solution.
Inferring Types | tRPC
It is often useful to access the types of your API within your clients. For this purpose, you are able to infer the types contained in your AppRouter.