Skip to content

Commit

Permalink
feat: add 404 handler
Browse files Browse the repository at this point in the history
  • Loading branch information
nistei authored and Benjozork committed Apr 23, 2022
1 parent 4db62f6 commit f34f59f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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: [
Expand Down Expand Up @@ -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 {
}
24 changes: 24 additions & 0 deletions src/utilities/not-found.filter.ts
Original file line number Diff line number Diff line change
@@ -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<Response>();
const request = ctx.getRequest<Request>();
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,
});
}
}

0 comments on commit f34f59f

Please sign in to comment.