我有 2 个服务,一个生产者和另一个消费者。我在消费者中创建了一个 RPCException 来测试它。当生产者服务向消费者发送 RPC 消息并且消费者服务抛出 RPCException 时,我期望一个带有错误消息的对象来自生产者服务的 rpc 请求,但我得到了空对象 {} .我的问题是来自消费者的响应消息是空对象,但我期望一个带有错误代码或错误消息的对象。
生产者 main.ts:
import { NestFactory } from '@nestjs/core';
import { ApiGatewayConfigService } from './api-gateway.config.service';
import { ApiGatewayModule } from './api-gateway.module';
import * as sourceMapSupport from 'source-map-support';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { ExceptionFilter } from '@shared/shared/rpc-exception.filter';
async function bootstrap() {
sourceMapSupport.install();
const app = await NestFactory.create<NestFastifyApplication>(
ApiGatewayModule,
new FastifyAdapter()
);
const configService = app.get(ApiGatewayConfigService);
app.useGlobalFilters(new ExceptionFilter());
app.useGlobalPipes(
new ValidationPipe({
transform: true,
transformOptions: {
enableImplicitConversion: true
},
whitelist: true,
forbidNonWhitelisted: true,
disableErrorMessages: configService.APP_ENVIRONMENT === 'production'
})
);
app.enableShutdownHooks();
await app.listen(configService.APP_LISTENING_PORT, '0.0.0.0');
}
bootstrap();
制作人服务:
async page(privileges: UserPrivileges, acceptLanguage: string): Promise<any> {
const result = await this.amqpConnection.request<any>({
exchange: process.env.API_GATEWAY_RABBITMQ_EXCHANGE_NAME,
routingKey: 'trend_specific_test',
payload: {
options:{
from: 0,
limit: 21,
privileges
},
acceptLanguage
},
});
console.log(result);
}
消费者服务:
import { NestFactory } from '@nestjs/core';
import { TrendModule } from './trend.module';
async function bootstrap() {
const app = await NestFactory.createApplicationContext(TrendModule);
}
bootstrap();
消费者服务:
@UseFilters(new ExceptionFilter())
@RabbitRPC({
exchange: RABBITMQ_EXCHANGE_NAME,
routingKey: 'trend_specific_test',
queue: 'trend_specific_test',
allowNonJsonMessages: true,
})
async dailyPlaylists(msg: {options: SearchOptions, acceptLanguage: string}): Promise<any> {
return this.trendDataService.testMethod(msg.options, msg.acceptLanguage);
}
消费者数据服务:
async testMethod(options: SearchOptions, acceptLanguage: string): Promise<any> {
throw new RpcException('Invalid credentials.');
}
rpc-exception.filter.ts
import { Catch, RpcExceptionFilter, ArgumentsHost } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { RpcException } from '@nestjs/microservices';
@Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
return throwError(() => exception.getError());
}
}
你解决了吗?面临同样的问题。