【问题标题】:NestJS exception filter for MongoError returns UnhandledPromiseRejectionWarning用于 MongoError 的 NestJS 异常过滤器返回 UnhandledPromiseRejectionWarning
【发布时间】:2020-08-23 20:11:42
【问题描述】:

我正在尝试通过 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,
      });
  }
}

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

    问题是“MongoError”在 mongoose 包中不直接可用,并且 mongodb 包中的 MongoError 与 mongoose 使用的不同。解决方法很简单,在mongoose-exception.filter.ts文件中,我将import改为:

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

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 2019-06-28
      • 2020-08-28
      • 2021-11-05
      相关资源
      最近更新 更多