我对 NestJs 很陌生,但是我最近要详细说明的问题更多的是异步异常处理问题。我有一个 http post 函数,负责在 mongodb 中插入用户,以防找不到具有该 id 的任何其他用户。由于 findOne 函数是异步的,因此当存在重复用户时我不能抛出异常。这是我的控制器:
@Post('/register')
async register(@Body() createUserDto: User): Promise<String> {
return await this.sejamService.registerUser(createUserDto);
}
Run Code Online (Sandbox Code Playgroud)
我的用户服务:
try {
this.findOne(userProfile.nationalCode).then(res => {
if (res === undefined) {
var user = new User(userProfile.nationalCode, userProfile.email, userProfile.password, userProfile.firstName,
userProfile.surname, userProfile.fatherName, userProfile.birthCertNumber, userProfile.phoneNumber);
//const createdUser = new this.userModel(userProfile);
this.usersRepository.save(user);
} else {
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: 'some error',
}, HttpStatus.CONFLICT);
}
});
} catch (e) {
console.log('error');
throw new HttpException({
status: HttpStatus.BAD_REQUEST,
error: 'some error', …Run Code Online (Sandbox Code Playgroud)