From 8ca2d07df6ed14e06a7c781481e1a78cfc3b08a4 Mon Sep 17 00:00:00 2001 From: Niklas Steiner Date: Sat, 23 Apr 2022 20:09:40 +0200 Subject: [PATCH] feat: add 404 handler --- src/app.module.ts | 9 ++++++++- src/utilities/not-found.filter.ts | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/utilities/not-found.filter.ts diff --git a/src/app.module.ts b/src/app.module.ts index 4fef7ff..de5e19e 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -4,6 +4,7 @@ import { ConfigModule, ConfigService } from '@nestjs/config'; import { ScheduleModule } from '@nestjs/schedule'; import { WinstonModule } from 'nest-winston'; import * as winston from 'winston'; +import { APP_FILTER } from '@nestjs/core'; import { AppController } from './app.controller'; import { MetarController } from './metar/metar.controller'; import { MetarService } from './metar/metar.service'; @@ -26,6 +27,7 @@ import { IvaoService } from './utilities/ivao.service'; import { GnssModule } from './gnss/gnss.module'; import { CpdlcController } from './cpdlc/cpdlc.controller'; import { CpdlcService } from './cpdlc/cpdlc.service'; +import { NotFoundExceptionFilter } from './utilities/not-found.filter'; @Module({ imports: [ @@ -124,7 +126,12 @@ import { CpdlcService } from './cpdlc/cpdlc.service'; AtcController, CpdlcController, ], - providers: [MetarService, AtisService, TafService, VatsimService, IvaoService, AtcService, CpdlcService], + providers: [ + { + provide: APP_FILTER, + useClass: NotFoundExceptionFilter, + }, + MetarService, AtisService, TafService, VatsimService, IvaoService, AtcService, CpdlcService], }) export class AppModule { } diff --git a/src/utilities/not-found.filter.ts b/src/utilities/not-found.filter.ts new file mode 100644 index 0000000..3d17c33 --- /dev/null +++ b/src/utilities/not-found.filter.ts @@ -0,0 +1,24 @@ +import { ArgumentsHost, Catch, ExceptionFilter, Logger, NotFoundException } from '@nestjs/common'; + +@Catch(NotFoundException) +export class NotFoundExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(NotFoundExceptionFilter.name); + + catch(exception: NotFoundException, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + const status = exception.getStatus(); + + this.logger.log(`404 '${request.url}' '${JSON.stringify(request.headers)}'`); + + response + // @ts-ignore + .status(status) + .json({ + statusCode: status, + timestamp: new Date().toISOString(), + path: request.url, + }); + } +}