TanStackT
TanStack7mo ago
2 replies
dual-salmon

How to handle server errors on the client side?

Hello, I am trying to learn TanStack Start and I want to show the error on the client side when an error occurs during RPC. How can I do this? Is it possible to subscribe to the states of the RPC on the server side without using a hook like useMutation? When using tRPC, we could catch errors thrown on the server side on the client side.

I have this RPC:

// src/lib/functions/server.examResult.functions.ts
export const createExamResult = createServerFn({ method: "POST" })
  .middleware([authMiddleware])
  .validator(createExamResultSchema)
  .handler(async ({ context, data }) => {
    const user = context.user;

    const hasExamResult = await db.query.examResult.findFirst({
      where: and(eq(examResult.userId, user.id), eq(examResult.examType, data.examType)),
    });

    if (hasExamResult) {
      throw new Error(`You already have a ${data.examType} exam result`);
    }

    const result = await db.insert(examResult).values({
      userId: user.id,
      approvalStatus: "pending",
      examType: data.examType,
      score: data.score,
      documentBase64: data.imageBase64,
    });

    if (result.length === 0) {
      throw new Error(`Failed to create ${data.examType} exam result`);
    }

    return {
      success: true,
      message: `${data.examType} exam result created successfully`,
    };
  });
`

and I have this hook:

// src/hooks/use-create-exam.ts
export function useCreateExam() {
  const router = useRouter();
  const queryClient = useQueryClient();
  const _createExam = useServerFn(createExamResult);

  return useCallback(
    async (data: CreateExamResult) => {
      const result = await _createExam({ data });

      router.invalidate();
      queryClient.invalidateQueries({ queryKey: QUERY_KEYS.EXAM_RESULTS });

      return result;
    },
    [router, queryClient, _createExam],
  );
}


How can I handle server-side errors on the client side?
image.png
Was this page helpful?