I would like to set up a filter to catch mongo errors (I'm using mongoose on this project) but nothing I do works and my research / test of what is on the internet does nothing.
mongoExceptionFilter.ts
import {
ArgumentsHost,
ConflictException,
BadRequestException,
Catch,
ExceptionFilter
} from '@nestjs/common';
import { MongoError } from 'mongodb';
@Catch(MongoError)
export class MongoExceptionFilter implements ExceptionFilter {
catch(exception: MongoError, host: ArgumentsHost): unknown {
switch (exception.code) {
case 11000: // duplicate exception
throw new ConflictException();
default:
throw new BadRequestException(`error ${exception.code}`);
}
}
}
I test a call here main.ts
:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new MongoExceptionFilter());
await app.listen(3001);
}
and here users.controller.ts
:
@Post()
@UseFilters(MongoExceptionFilter)
createUser(@Body() body: UsersDto): Promise<Users> {
return this.userService.createUser(body.name, body.password);
}
Some link i found just for information :