Skip to content

Commit

Permalink
Fix inaccurate type of setErrorHandler (#2092)
Browse files Browse the repository at this point in the history
* fix: type of `setErrorHandler`

* fix: use generic instead of any

* add test for the type of `setErrorHandler`
  • Loading branch information
chengluyu committed Feb 13, 2020
1 parent f971751 commit 743ad74
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion fastify.d.ts
Expand Up @@ -693,7 +693,7 @@ declare namespace fastify {
/**
* Set a function that will be called whenever an error happens
*/
setErrorHandler(handler: (error: FastifyError, request: FastifyRequest<HttpRequest>, reply: FastifyReply<HttpResponse>) => void): void
setErrorHandler<E = FastifyError>(handler: (error: E, request: FastifyRequest<HttpRequest>, reply: FastifyReply<HttpResponse>) => void): void

/**
* Set a function that will be called whenever an error happens
Expand Down
24 changes: 24 additions & 0 deletions test/types/index.ts
Expand Up @@ -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<AuthenticationError | DatabaseError>((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}`
Expand Down

0 comments on commit 743ad74

Please sign in to comment.