mongoose MongoError的NestJS异常过滤器返回UnhandledPromiseRejectionWarning

qyswt5oh  于 2023-05-07  发布在  Go
关注(0)|答案(3)|浏览(262)

我试图通过Mongoose为Mongo错误创建一个自定义异常过滤器。当我使用过滤器时,出现UnhandledPromiseRejectionWarning,并且没有结果。你知道我该怎么补救吗

错误: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,
      });
  }
}
xxslljrj

xxslljrj1#

问题是mongoError不能直接在mongoose包中使用,mongodb包中的MongoError与mongoose使用的不一样。解决方案非常简单,在mongoose-exception.filter.ts文件中,我将导入更改为:

import { MongoError } from 'mongoose/node_modules/mongodb';
4uqofj5v

4uqofj5v2#

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)}'`,
        );
    }
  }
}
13z8s7eq

13z8s7eq3#

试着这样做。

import { Error } from 'mongoose';

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

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

相关问题