-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorHandler.ts
More file actions
38 lines (31 loc) · 1.16 KB
/
Copy patherrorHandler.ts
File metadata and controls
38 lines (31 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { STATUS_CODES } from 'node:http'
import type { FastifyError, FastifyPluginAsync } from 'fastify'
import fastifyPlugin from 'fastify-plugin'
import resolveErrorStatus from '@/lib/resolveErrorStatus'
const errorHandler: FastifyPluginAsync = async (fastify) => {
fastify.setErrorHandler<FastifyError>((error, request, reply) => {
const { statusCode, trustMessage } = resolveErrorStatus(error)
const isClientError = statusCode >= 400 && statusCode < 500
const statusName = STATUS_CODES[statusCode] ?? 'Error'
if (isClientError) {
request.log.warn({ err: error }, 'Client error')
void reply.code(statusCode).send({
error: statusName,
message: trustMessage ? error.message : statusName,
})
return
}
request.log.error({ err: error }, 'Unhandled server error')
void reply.code(statusCode).send({
error: statusName,
message: 'Internal server error',
})
})
fastify.setNotFoundHandler((request, reply) => {
void reply.code(404).send({
error: 'Not Found',
message: `Route ${request.method}:${request.url} not found`,
})
})
}
export default fastifyPlugin(errorHandler)