Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

1.0 KB
Raw Blame
import { FastifyPluginCallback } from 'fastify';
import fp from 'fastify-plugin';
import { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod';

import { ApiErrorCode } from '@colanode/core';
import { createLogger } from '@colanode/server/lib/logger';

const logger = createLogger('api:client:error-handler');

export const errorHandlerCallback: FastifyPluginCallback = (
  fastify,
  _,
  done
) => {
  fastify.setErrorHandler(async (error, _, reply) => {
    logger.error(error, `Error processing request`);

    // TODO: return detailed validation errors
    if (hasZodFastifySchemaValidationErrors(error)) {
      return reply.code(400).send({
        code: ApiErrorCode.ValidationError,
        message:
          'One or more fields are invalid. Please check your request and try again.',
      });
    }

    return reply.code(500).send({
      code: ApiErrorCode.Unknown,
      message: 'An unexpected error occurred. Please try again later.',
    });
  });

  done();
};

export const errorHandler = fp(errorHandlerCallback);