Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save muneneevans/3e6b8264ef7a3b1ed8310783faa2e86a to your computer and use it in GitHub Desktop.
Save muneneevans/3e6b8264ef7a3b1ed8310783faa2e86a 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment