Skip to content

Commit

Permalink
feat: add entityNotFoundExceptionFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
allohamora committed Dec 16, 2021
1 parent b275d8d commit 2960905
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { EntityNotFoundExceptionFilter } from './utils/entity-not-found-exception.filter';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new EntityNotFoundExceptionFilter());

await app.listen(3000);
}
bootstrap();
15 changes: 15 additions & 0 deletions src/utils/entity-not-found-exception.filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
import { EntityNotFoundError } from 'typeorm';
import { Response } from 'express';

@Catch(EntityNotFoundError)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
public catch(exception: EntityNotFoundError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();

const statusCode = 404;

return response.status(statusCode).json({ statusCode, message: 'Not Found' });
}
}

0 comments on commit 2960905

Please sign in to comment.