Skip to content

Instantly share code, notes, and snippets.

@gsusmonzon
Last active August 21, 2024 10:40
Show Gist options
  • Save gsusmonzon/ecd7842495f07594761e40c2758617d0 to your computer and use it in GitHub Desktop.
Save gsusmonzon/ecd7842495f07594761e40c2758617d0 to your computer and use it in GitHub Desktop.
Make NestJs returns 404 when EntityNotFoundError exception is thrown

Make NestJs returns 404 when EntityNotFoundError exception is thrown

When using findOrFail() or findOneOrFail() from typeORM, a 500 error is returned if there is no entity (EntityNotFoundError).

To make it returns a 404, use an exception filter as described in https://docs.nestjs.com/exception-filters .

file /src/filters/entity-not-found-exception.filter.ts

import { Catch, ExceptionFilter, ArgumentsHost} from "@nestjs/common";
import { EntityNotFoundError } from 'typeorm/error/EntityNotFoundError'
import { Response } from 'express';


/**
 * Custom exception filter to convert EntityNotFoundError from TypeOrm to NestJs responses
 * @see also @https://docs.nestjs.com/exception-filters
 */
@Catch(EntityNotFoundError, Error)
export class EntityNotFoundExceptionFilter implements ExceptionFilter {
  public catch(exception: EntityNotFoundError, host: ArgumentsHost) {

    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    return response.status(404).json({ message: { statusCode: 404, error: 'Not Found', message: exception.message } });
  }
}

Use it in your main module

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { EntityNotFoundExceptionFilter } from './filters/entity-not-found-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new EntityNotFoundExceptionFilter());
  await app.listen(3000);
}
bootstrap();
@micobarac
Copy link

micobarac commented Aug 21, 2024

Add cases of specific TypeORMError or any other error that needs special treatment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment