Skip to content

Commit

Permalink
feat(error): support handling not found route error
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Nov 19, 2024
1 parent 215b96e commit 65eac6d
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 3 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/http",
"version": "5.3.0",
"version": "5.4.0",
"description": "The Athenna Http server. Built on top of fastify.",
"license": "MIT",
"author": "João Lenon <[email protected]>",
Expand Down
23 changes: 23 additions & 0 deletions src/handlers/FastifyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { RequestHandler } from '#src/types/contexts/Context'
import type { ErrorHandler } from '#src/types/contexts/ErrorContext'
import type { InterceptHandler, TerminateHandler } from '#src/types'
import type { FastifyReply, FastifyRequest, RouteHandlerMethod } from 'fastify'
import { NotFoundException } from '#src/exceptions/NotFoundException'

export class FastifyHandler {
/**
Expand Down Expand Up @@ -117,4 +118,26 @@ export class FastifyHandler {
await handler(ctx)
}
}

/**
* Parse the fastify not found route handler.
*/
public static notFoundError(handler: ErrorHandler) {
return async (req: FastifyRequest, res: FastifyReply) => {
if (!req.data) {
req.data = {}
}

const ctx: any = {}

ctx.data = req.data
ctx.request = new Request(req)
ctx.response = new Response(res, ctx.request)
ctx.error = new NotFoundException(
`Route ${req.method}:${req.url} not found`
)

await handler(ctx)
}
}
}
1 change: 1 addition & 0 deletions src/server/ServerImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export class ServerImpl {
*/
public setErrorHandler(handler: ErrorHandler): ServerImpl {
this.fastify.setErrorHandler(FastifyHandler.error(handler))
this.fastify.setNotFoundHandler(FastifyHandler.notFoundError(handler))

return this
}
Expand Down

0 comments on commit 65eac6d

Please sign in to comment.