简体   繁体   English

在nestJs异步function中抛出HttpException

[英]Throw HttpException in nestJs async function

Im new to nestJs, however my recent problem which im going to elaborate, is more of an async exception handling issue.我是nestJs的新手,但是我最近要详细说明的问题更多的是异步异常处理问题。 i have a http post function which is responsible for inserting a user in mongodb in case of not finding any other user with that id.我有一个 http 后 function 负责在 mongodb 中插入用户,以防找不到具有该 ID 的任何其他用户。 Since the findOne function is async, i can not throw exception when a duplicate user exists.由于 findOne function 是异步的,当存在重复用户时,我不能抛出异常。 here is my controller:这是我的 controller:

  @Post('/register')
    async register(@Body() createUserDto: User): Promise<String> {
       return await this.sejamService.registerUser(createUserDto);

    }

my userService:我的用户服务:

  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',
                }, HttpStatus.CONFLICT);
            }

Since I'm not able to test this code, I'll try to sketch a possible solution.由于我无法测试此代码,我将尝试绘制一个可能的解决方案。

First, I'll start by stating that in my opinion, throwing http exceptions from within services is not the best practice, since ideally, services should not be aware of that context.首先,我首先要说明的是,在我看来,从服务中抛出http异常并不是最佳实践,因为理想情况下,服务不应该知道该上下文。 There are obviously exceptions, your's doesn't seems like one of them (again - this is my opinion).显然有例外,你的似乎不是其中之一(再次 - 这是我的观点)。

As for the "solution" itself, you can take advantages of Promise s, for instance:至于“解决方案”本身,您可以利用Promise的优势,例如:

userService (this is just a piece of the code): userService(这只是一段代码):

return new Promise((resolve, reject) => {
    this.findOne(userProfile.nationalCode).then(() => {
    if (res === undefined) {
        const 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);
        resolve();
    } else {
        reject('some error');
    }
})
   ...

With that code in your hand, you would be able to do something like this in your controller:有了该代码,您就可以在 controller 中执行以下操作:

@Post('/register')
async register(@Body() createUserDto: User): Promise<String> {
  try {
     await this.sejamService.registerUser(createUserDto);
  } catch(e) {
     throw new HttpException(....)
  }
}

Again, the above code is just an example.同样,上面的代码只是一个示例。 Do whatever you need to do to make it more fit.做任何你需要做的事情来让它更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM