From 8930978b9fe0eb63e1ca40caec465654f49999e0 Mon Sep 17 00:00:00 2001 From: Bruno Fernandes Date: Wed, 12 Jun 2024 09:15:16 -0300 Subject: [PATCH] implements global error handling --- src/infra/app.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/infra/app.ts b/src/infra/app.ts index a64db42..ae86c51 100644 --- a/src/infra/app.ts +++ b/src/infra/app.ts @@ -4,6 +4,9 @@ import { resolve } from 'node:path' import { readFileSync } from 'node:fs' import { orgRoutes } from './http/routes/org-routes' import { petRoutes } from './http/routes/pet-routes' +import { env } from '@/env/env' +import { ZodError } from 'zod' +import { DataValidationError } from '@/core/errors/errors/data-validation-error' export const app = fastify() @@ -23,3 +26,20 @@ app.register(fastifyJwt, { app.register(orgRoutes) app.register(petRoutes, { prefix: '/pets' }) + +app.setErrorHandler((err, _req, res) => { + if (env.NODE_ENV !== 'prod') { + console.error(err) + } + if (err instanceof ZodError) { + return res + .status(400) + .send({ message: 'Validation error', issues: err.format() }) + } + if (err instanceof DataValidationError) { + return res + .status(400) + .send({ message: 'Validation error', issues: err.message }) + } + return res.status(500).send({ message: 'Internal server error.' }) +})