diff --git a/fastify.d.ts b/fastify.d.ts index 8465b613ec..8b20ff551c 100644 --- a/fastify.d.ts +++ b/fastify.d.ts @@ -693,7 +693,7 @@ declare namespace fastify { /** * Set a function that will be called whenever an error happens */ - setErrorHandler(handler: (error: FastifyError, request: FastifyRequest, reply: FastifyReply) => void): void + setErrorHandler(handler: (error: E, request: FastifyRequest, reply: FastifyReply) => void): void /** * Set a function that will be called whenever an error happens diff --git a/test/types/index.ts b/test/types/index.ts index 7ec282674c..abec2cb601 100644 --- a/test/types/index.ts +++ b/test/types/index.ts @@ -519,6 +519,30 @@ server.setErrorHandler((err, request, reply) => { } }) +// Libraries may define their own error types +class AuthenticationError extends Error { + public constructor (public data: string) { + super() + } +} + +class DatabaseError extends Error { + public constructor (public query: string) { + super() + } +} + +// Users can deal with those errors via error handlers +server.setErrorHandler((err, request, reply) => { + if (err instanceof AuthenticationError) { + server.log.error(err.data) + reply.send(err.message) + } else { + server.log.error(err.query) + reply.send(err.message) + } +}) + server.setReplySerializer((payload, statusCode) => { if (statusCode === 201) { return `Created ${payload}`