T
TanStack4w ago
xenial-black

How to handle Errors in catch?

Hey, I am relatively new to TypeScript, but I want to learn. I need some help here.
export const Route = createFileRoute("/app")({
beforeLoad: async ({ context: { queryClient }, location }) => {
try {
const user = await queryClient.ensureQueryData(currentUserQueryOptions());
return { user };
} catch (error) { // error is of type unknown.
if (error.status === 401) {
throw redirect({ to: "/login", search: { redirect: location.href } });
} else {
throw error;
}
}
},
component: App,
});
export const Route = createFileRoute("/app")({
beforeLoad: async ({ context: { queryClient }, location }) => {
try {
const user = await queryClient.ensureQueryData(currentUserQueryOptions());
return { user };
} catch (error) { // error is of type unknown.
if (error.status === 401) {
throw redirect({ to: "/login", search: { redirect: location.href } });
} else {
throw error;
}
}
},
component: App,
});
I think this has nothing to do with tanstack query. I think this is JS TS specific. How you handle this? With guards? I tried it to solve like that:
if (error instanceof Error && "status" in error && error.status === 401) {
if (error instanceof Error && "status" in error && error.status === 401) {
but that seems not to be the final conclusion of wisdom. Thanks
1 Reply
deep-jade
deep-jade4w ago
Hey, I'd like to address some other things as well. ensureQueryData doesn't throw - it just continues with an error. Meaning, the cache entry for currentUser will have status error, and then your code just goes to the next line as if everything is fine. What you actually want is fetchQuery(), this call throws if the queryFn throws. What does your throw look like in the queryFn of currentUserQueryOptions? Do you call const res = fetch() and then, if !res.ok then you throw res? If that's the case, then there should be no problem to say:
} catch (error) { // error is of type unknown.
if (error instanceof Response && error.status === 401) {
throw redirect({ to: "/login", search: { redirect: location.href } });
} else {
throw error;
}
}
} catch (error) { // error is of type unknown.
if (error instanceof Response && error.status === 401) {
throw redirect({ to: "/login", search: { redirect: location.href } });
} else {
throw error;
}
}
If you're using Axios, then you'll have to do the "status" in error check I think

Did you find this page helpful?