NestJS exception filter for MongoError returns UnhandledPromiseRejectionWarning

Viewed 1713

I'm trying to create a custom exception filter for Mongo errors through Mongoose. When I use the filter, an UnhandledPromiseRejectionWarning occures and it gives no result. Any idea how I can fix this?

Error: UnhandledPromiseRejectionWarning: TypeError: Right-hand side of 'instanceof' is not an object

users.controller.ts

import { Body, Controller, Post, UseFilters } from '@nestjs/common';
import { UsersService } from './users.service';
import { RegisterUserDto } from './dto/register-user.dto';
import { MongooseExceptionFilter } from './filters/mongoose-exception.filter';

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @UseFilters(MongooseExceptionFilter)
  @Post('register')
  register(@Body() registerDto: RegisterUserDto) {
    return this.usersService.create(registerDto);
  }
}

mongoose-exception.filter.ts

import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Request, Response } from 'express';
import { MongoError } from 'mongoose';

@Catch(MongoError)
export class MongooseExceptionFilter implements ExceptionFilter {
  catch(exception: MongoError, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    // const status = exception.getStatus();
    console.log('Exception', exception);

    response
      .status(418)
      .json({
        statusCode: 418,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}
3 Answers

The problem was that "MongoError" was not available in the mongoose package directly and that MongoError from the mongodb package wasn't the same as the one mongoose was using. The solution was very simple, in the mongoose-exception.filter.ts file, I changed the import to:

import { MongoError } from 'mongoose/node_modules/mongodb';
import {
  ArgumentsHost,
  Catch,
  ConflictException,
  ExceptionFilter,
} from '@nestjs/common';
import { MongoServerError } from 'mongodb';
import * as mongoose from 'mongoose';


@Catch(mongoose.mongo.MongoServerError)
export class MongoExceptionFilter implements ExceptionFilter {
  catch(exception: MongoServerError, host: ArgumentsHost) {
    switch (exception.code) {
      case 11000:
        throw new ConflictException(
          `Duplicate unique key '${Object.keys(exception.keyValue)}'`,
        );
    }
  }
}

Try to do this.

import { Error } from 'mongoose';

@Catch(Error.ValidationError)
export class MongooseExceptionFilter implements ExceptionFilter {

  catch(exception: Error.ValidationError, host: ArgumentsHost) {
  
  }
}
Related