我试图通过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,
});
}
}
3条答案
按热度按时间xxslljrj1#
问题是mongoError不能直接在mongoose包中使用,mongodb包中的MongoError与mongoose使用的不一样。解决方案非常简单,在
mongoose-exception.filter.ts
文件中,我将导入更改为:4uqofj5v2#
13z8s7eq3#
试着这样做。