问题描述
我从 https://docs.nestjs.com/techniques/mongodb
问题是当出现猫鼬验证错误时(例如,我有一个带有必填字段的架构,但未提供):
The issue is when there is a mongoose validation error (e.g i have a schema with a required field and it isn't provided):
来自games.service.ts:
From games.service.ts:
async create(createGameDto: CreateGameDto): Promise<IGame> {
const createdGame = new this.gameModel(createGameDto);
return await createdGame.save();
}
save()函数返回一个Promise.
The save() function returns a Promise.
现在我在game.controller.ts
Now i have this in the game.controller.ts
@Post()
async create(@Body() createGameDto: CreateGameDto) {
this.gamesService.create(createGameDto);
}
处理错误然后返回具有不同http状态(可能是json文本)的响应的最佳方法是什么?您通常会抛出一个HttpException
,但是从哪里来?如果我在promise中使用.catch()处理错误,我将无法做到这一点.
What is the best way to handle an error and then return a response with a different http status and maybe a json text?You would usually throw a HttpException
but from where? I can't do that if i handle the errors using .catch() in the promise.
(刚开始使用nestjs框架)
(Just started using the nestjs framework)
推荐答案
首先,您忘记在控制器内的create方法中添加return
.这是一个常见的,非常令人误解的错误,我犯了上千遍,花了我几个小时来调试.
First, you forgot to add return
in your create method inside the controller. This is a common, very misleading mistake I made a thousand of times and took me hours to debug.
要捕获异常:
您可以尝试使用@Catch
捕获MongoError.
You could try to catch MongoError using @Catch
.
对于我的项目,我正在执行以下操作:
For my projects I'm doing the following:
import { ArgumentsHost, Catch, ConflictException, ExceptionFilter } from '@nestjs/common';
import { MongoError } from 'mongodb';
@Catch(MongoError)
export class MongoExceptionFilter implements ExceptionFilter {
catch(exception: MongoError, host: ArgumentsHost) {
switch (exception.code) {
case 11000:
// duplicate exception
// do whatever you want here, for instance send error to client
}
}
}
然后您可以在控制器中像这样使用它(甚至可以将其用作全局/类范围的过滤器):
You can then just use it like this in your controller (or even use it as a global / class scoped filter):
import { MongoExceptionFilter } from '<path>/mongo-exception.filter';
@Get()
@UseFilters(MongoExceptionFilter)
async findAll(): Promise<User[]> {
return this.userService.findAll();
}
(在findAll()调用中,重复的异常在这里没有意义,但您明白了.)
(Duplicate exception doesn't make sense here in a findAll() call, but you get the idea).
此外,我强烈建议您使用类验证器,如下所述: https://docs.nestjs. com/pipes
Further, I would strongly advise to use class validators, as described here: https://docs.nestjs.com/pipes
这篇关于如何使用NestJS处理猫鼬错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!