Nestjs 可以在服务中发送HTTP代码吗?

Nestjs 可以在服务中发送HTTP代码吗?,nestjs,Nestjs,我想知道是否可以从服务返回状态? 事实上,在我的服务中,我有允许注册的代码,但我想返回一个错误,例如,如果邮件中已经存在一个帐户。 我尝试了使用抛出新的HttpException(),但它没有改变任何东西 这是我目前的代码: 控制器: @Post('/signup') async signup(@Body() body): Promise<void> { return await this.accountService.signup(body); } @Post(“/si

我想知道是否可以从服务返回状态? 事实上,在我的服务中,我有允许注册的代码,但我想返回一个错误,例如,如果邮件中已经存在一个帐户。 我尝试了使用
抛出新的HttpException()
,但它没有改变任何东西

这是我目前的代码:

控制器:

@Post('/signup')
async signup(@Body() body): Promise<void> {
    return await this.accountService.signup(body);
}

@Post(“/signup”)
异步注册(@Body()Body):承诺{
返回等待此。accountService。注册(正文);
}
服务:

async signup(body: IAccount): Promise<void> {
    const hashedPass: string = await bcrypt.hash(body.password, await bcrypt.genSalt(10));
    const account: IAccount = {
        'uuid': uuidv4(),
        'username': body.username,
        'password': hashedPass
    };
    const newAccount = new this.accountModel(account)
    newAccount.save()
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
    })
}
异步注册(主体:IAccount):承诺{ const hashedPass:string=await bcrypt.hash(body.password,await bcrypt.genSalt(10)); 常量帐户:IAccount={ “uuid”:uuidv4(), “用户名”:body.username, “密码”:hashedPass }; const newAccount=newthis.accountModel(account) newAccount.save() .然后(功能(响应){ 控制台日志(响应); }) .catch(函数(错误){ 抛出新的HttpException('Forbidden',HttpStatus.Forbidden); }) }
感谢advance

您永远不会从该方法返回任何内容。您至少应该返回
newAccount.save()
,以便
await
可以实际等待
catch
的响应,如果出现错误

ok,我将进行等待,但如何发送HTTP代码来说明邮件已被使用?因为它返回一个201,即使它在catchread中,它发送一个201的原因是因为该方法没有实际等待的内容。您正在运行承诺,并最终抛出一个错误,但您不会让JS在离开方法之前等待承诺的结果。这就是为什么您需要
返回newAccount.save().then().catch()
。或者您需要
等待newAccount.save().then().catch()
,但无论如何,您都需要等待承诺完成后再发送响应。