小编dav*_*ui6的帖子

如何在 NestJS 中处理 RpcException

我正在尝试构建一个包含多个微服务的 NestJS 后端和一个作为与微服务通信的网关的 REST API。对于网关和微服务之间的通信,我使用 gRPC。简单的通信已经可以工作,但现在我想在微服务中实现错误处理。NestJS 文档指出,这可以通过 RpcException 类实现。https://docs.nestjs.com/microservices/exception-filters但是,如果我尝试捕获网关 API 中的异常,我只会收到“ERROR [ExceptionsHandler] 2 UNKNOWN:...”,然后是异常错误消息。

网关API:user.controller.ts

import { Controller, Get, Param } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { UserViewModel } from '../../proto/build/service-name/user';
import { UserService } from './user.service';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get(':id')
  async getUserById(@Param('id') id: number): Promise<UserViewModel> {
    try {
      return await this.userService.getUserById(id);
    } catch (error) {
      return error;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

网关API:user.service.ts

import { Inject, Injectable, OnModuleInit …
Run Code Online (Sandbox Code Playgroud)

grpc nestjs nestjs-gateways

3
推荐指数
1
解决办法
8884
查看次数

标签 统计

grpc ×1

nestjs ×1

nestjs-gateways ×1