Skip to content

Commit

Permalink
Merge pull request #7 from bruno-valero/dev
Browse files Browse the repository at this point in the history
implements global error handling
  • Loading branch information
bruno-valero authored Jun 12, 2024
2 parents 03793a9 + 8930978 commit f1b3333
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/infra/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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.' })
})

0 comments on commit f1b3333

Please sign in to comment.