From 65eac6d8312f5ff28ae6864ef77beeb33ad9aaf5 Mon Sep 17 00:00:00 2001 From: jlenon7 Date: Tue, 19 Nov 2024 16:57:19 +0000 Subject: [PATCH] feat(error): support handling not found route error --- package-lock.json | 4 ++-- package.json | 2 +- src/handlers/FastifyHandler.ts | 23 +++++++++++++++++++++++ src/server/ServerImpl.ts | 1 + 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index c9252e1..fb1dde3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@athenna/http", - "version": "5.3.0", + "version": "5.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@athenna/http", - "version": "5.3.0", + "version": "5.4.0", "license": "MIT", "devDependencies": { "@athenna/artisan": "^5.1.0", diff --git a/package.json b/package.json index 94d4bce..b0fefec 100644 --- a/package.json +++ b/package.json @@ -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 ", diff --git a/src/handlers/FastifyHandler.ts b/src/handlers/FastifyHandler.ts index 95f3383..c781266 100644 --- a/src/handlers/FastifyHandler.ts +++ b/src/handlers/FastifyHandler.ts @@ -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 { /** @@ -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) + } + } } diff --git a/src/server/ServerImpl.ts b/src/server/ServerImpl.ts index ae182ce..1c26c48 100644 --- a/src/server/ServerImpl.ts +++ b/src/server/ServerImpl.ts @@ -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 }