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();
Add cases of specific
TypeORMError
or any other error that needs special treatment.