NodeJS Nestjs抛出500内部服务器错误,而不是预期的错误

ctehm74n  于 2022-11-04  发布在  Node.js
关注(0)|答案(1)|浏览(378)

因此,我试图通过从nest @nestjs/common导入的HttpException模块将403 Forbidden错误从微服务抛出到网关,但nest一直将其作为500内部服务器错误抛出。
生成的错误的JSON.stringify为:

{"response":"User already exists","status":403,"message":"User already exists","name":"HttpException"}

网关中显示的错误为:

[Nest] 4747  - 11/06/2022, 18:01:58   ERROR [ExceptionsHandler] Internal server error
[Nest] 4747  - 11/06/2022, 18:01:58   ERROR [ExceptionsHandler] undefined

你知道这是怎么回事吗
下面是抛出错误的服务:

import { Model } from 'mongoose';
import {
  Injectable,
  Inject,
  ForbiddenException,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';

import { User, UserDocument } from './schemas/user.schema';

@Injectable()
export class AccountManagementService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
  async createUser(user: any): Promise<any> {
    const existingUser = await this.userModel.find({
      $or: [{ username: user.username }, { email: user.email }],
    });
    if (existingUser) {
      throw new HttpException('User already exists', HttpStatus.FORBIDDEN);
    }
    const createdUser = new this.userModel(user);
    return createdUser.save();
  }
}

这是控制器:

import { Controller, Post } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { AccountManagementService } from './account-management.service';

@Controller()
export class AccountManagementController {
  constructor(
    private accountManagementService: AccountManagementService,
  ) {}

  @MessagePattern({ cmd: 'createUser' })
  async createUser(userData: any): Promise<any> {
    return this.accountManagementService
      .createUser(userData)
  }
}
w6mmgewl

w6mmgewl1#

因此,我基本上是在controllers的try和catch块中处理从服务抛出的错误,这样,从服务捕获的任何错误都会以正确的状态代码和描述user.controller.ts抛出。

import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthDto, SigninDto } from './dto';

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

  @HttpCode(HttpStatus.OK)
  @Post('signin')
  async signin(@Body() dto: SigninDto) {
    try {
      return this.authService.signin(dto);
    } catch (error) {
      throw error;
    }
  }

  @Post('signup')
  async signup(@Body() dto: AuthDto) {
    try {
      return this.authService.signup(dto);
    } catch (error) {
      throw error;
    }
  }
}

那么这就是我在用户服务中的注册功能

async signup(dto: AuthDto): Promise<any> {
const account = await this.userModel.findOne({
  phoneNumber: dto.phoneNumber,
});
if (account) {
  throw new ForbiddenException(
    'An account with this phoneNumber already exists',
  );
}
const SALT = 10;
const hashedPassword = await bcrypt.hash(dto.password, SALT);
const newUser = await this.userService.create({
  name: dto.name,
  password: hashedPassword,
  phoneNumber: dto.phoneNumber,
});
return newUser;

}

相关问题