1
votes

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 :

3

3 Answers

0
votes

Same problem here. The only solution for me now is to catch the MongoError imported from mongodb in the global filter and check for it there

0
votes

As per this MongoError from MongoDb is different from MongoError from mongoose package. So it seems you are using both the packages i.e. Mongodb and mongoose.

0
votes

With Custom messages, I combined solutions from answers How to handle mongoose error with nestjs

import { ArgumentsHost, Catch, ExceptionFilter, RpcExceptionFilter } from '@nestjs/common';
import { Error } from 'mongoose';
import { IDTOError } from '../errors/bad-request-exception.error';
import ValidationError = Error.ValidationError;
import { MongoError } from 'mongodb';


@Catch(MongoError)
export class MongoExceptionFilter implements ExceptionFilter {
  catch(exception: MongoError, host: ArgumentsHost) {
    // switch (exception.code) {
    //   case 11000:
    //   default: console.log(exception,'ALERT ERROR CATCHED');
    //     // duplicate exception
    //     // do whatever you want here, for instance send error to client


    //     /** MAIGOD */
    // }
    const ctx = host.switchToHttp(),
      response = ctx.getResponse();

    return response.status(400).json(<IDTOError>{
      statusCode: 400,
      createdBy: 'ValidationErrorFilter, Schema or Model definition',
      errors: exception,
    });

  }
}

@Catch(ValidationError)
export class ValidationErrorFilter implements RpcExceptionFilter {

  catch(exception: ValidationError, host: ArgumentsHost): any {

    const ctx = host.switchToHttp(),
      response = ctx.getResponse();

    return response.status(400).json(<IDTOError>{
      statusCode: 400,
      createdBy: 'ValidationErrorFilter, Schema or Model definition',
      errors: exception.errors,
    });
  }
}