使用NestJS的未处理的承诺拒绝

时间:2020-09-06 01:05:57

标签: javascript node.js nestjs

当我执行以下代码时,我从服务器收到“ 201 Created”响应,但实际上没有将数据插入服务器。

我正在为我的应用程序使用带有TypeORM和Postgres的nestJS。

import { Repository, EntityRepository } from "typeorm";
import { User } from './user.entity';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { ConflictException, InternalServerErrorException } from "@nestjs/common";

@EntityRepository(User)
export class UserRepository extends Repository<User>{
    async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void>{
        const {username, password} = authCredentialsDto;

        const user = new User();
        user.username = username;
        user.password = password;

        try{
            await user.save();
        } catch (error) {
            if (error.code === '23505'){ // error code for duplicate value in a col of the server
                throw new ConflictException('Username already exists');
            } else {
                throw new InternalServerErrorException();
            }
        }      
    }
}

我在VS Code终端中得到以下响应,而不是从服务器获取“ 201 Crated”:

(node:14691) UnhandledPromiseRejectionWarning: Error: Username already exists
    at UserRepository.signUp (/home/rajib/practicing coding/nestJS-projects/nestjs-task-management/dist/auth/user.repository.js:24:23)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:14691) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14691) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

控制器模块代码如下:

import { Controller, Post, Body, ValidationPipe } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';

@Controller('auth')
export class AuthController {
    constructor( private authService: AuthService){}

    @Post('/signup')
    signUp(@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto): Promise<void>{
        return this.authService.signUp(authCredentialsDto);      
    }
}

1 个答案:

答案 0 :(得分:0)

美好的一天。

我认为您在这里遇到的问题不是等待对 AuthController 中的 authService.signup() 方法的方法调用...

所以,更正应该是:

在 AuthService::signup() 方法中:

return await this.userRepository.signup(authCredentialsDto);

在 AuthController::signup() 方法中:

return await this.authService.signup(authCredentialsDto);