小编Eli*_*i m的帖子

在nestJs异步函数中抛出HttpException

我对 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)

javascript nestjs

0
推荐指数
1
解决办法
7152
查看次数

标签 统计

javascript ×1

nestjs ×1