因此,我试图通过从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)
}
}
1条答案
按热度按时间w6mmgewl1#
因此,我基本上是在controllers的try和catch块中处理从服务抛出的错误,这样,从服务捕获的任何错误都会以正确的状态代码和描述user.controller.ts抛出。
那么这就是我在用户服务中的注册功能
}