TanStackT
TanStack6mo ago
1 reply
uncertain-scarlet

Centralized error handling

Hiii everyone, I am working on a huge educational project and we have a start frontend where the majority of serverFn's simply call another API

We haven't figured out yet how to handle errors in a centralized manner, and this is forcing us to do a nasty try...catch everywhere, it is verbose and IMO unecessary, but we haven't found a better way yet

Example of how we are handling errors, in this case the analytics api is external to the frontend.
This pattern of having an auth check + the try...catch for the operation is repeated everywhere in our frontend, and I am looking for ways to better handle this in a centralized

From what I found in the chats global middlewares are not working atm

export const getActivityMetrics = createServerFn({
  method: 'POST',
})
  .middleware([userAuthMiddleware, apiAuthMiddleware])
  .validator(
    zodValidator(
      z.object({
        startDate: z.string().datetime(),
        endDate: z.string().datetime(),
        studentId: z.string(),
        timezone: z.string().optional(),
      })
    )
  )
  .handler(async ({ context, data }) => {
    const { cognitoUser, analyticsApi } = context;

    if (!cognitoUser) {
      setResponseStatus(401);
      return {
        success: false,
        data: null,
        error: 'Unauthorized',
      };
    }

    const { startDate, endDate, studentId, timezone } = data;

    try {
      const response = await fetchActivityMetrics(analyticsApi, {
        startDate,
        endDate,
        studentId,
        timezone,
      });

      return {
        success: true,
        data: response,
      };
    } catch (error) {
      return handleServerFnError(
        error,
        {
          service: 'analytics-api',
          function: 'getActivityMetrics',
          endpoint: '/api/reports/activity',
          userId: cognitoUser.sub,
        },
        {
          statusCode: 500,
          clientMessage: 'Failed to fetch activity metrics',
        }
      );
    }
  });
Was this page helpful?