最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Throw HttpException in nestJs async function - Stack Overflow

programmeradmin4浏览0评论

Im new to nestJs, however my recent problem which im going to elaborate, is more of an async exception handling issue. 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. Since the findOne function is async, i can not throw exception when a duplicate user exists. here is my 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);
            }

Im new to nestJs, however my recent problem which im going to elaborate, is more of an async exception handling issue. 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. Since the findOne function is async, i can not throw exception when a duplicate user exists. here is my 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);
            }
Share Improve this question edited May 30, 2020 at 6:08 Eli m asked May 30, 2020 at 6:01 Eli mEli m 991 silver badge10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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. 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 Promises, for instance:

userService (this is just a piece of the code):

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:

@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.

发布评论

评论列表(0)

  1. 暂无评论