TanStackT
TanStack6mo ago
2 replies
verbal-lime

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,
});

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) {

but that seems not to be the final conclusion of wisdom.

Thanks
Was this page helpful?