I have setup a Microservice Architecture that looks the following:
- api-gateway (
NestFactory.create(AppModule);) - service 1 (
NestFactory.createMicroservice<MicroserviceOptions>) - service 2 (
NestFactory.createMicroservice<MicroserviceOptions>) ...
A Service looks like this:
service.controller.ts
service.handler.ts
Where handler is like a Service in a typical Monolith that handles the logic.
Currently, I am catching Exceptions the following way:
The handler makes a call to the database and fails due to a duplicated key (i.e. email).
I catch this exception and convert it to an
RpcExceptionIn the ApiGateway I catch the
RpcExceptionlike so:return new Promise<Type>((resolve, reject) => { this.clientProxy .send<Type>('MessagePattern', { dto: DTO }) .subscribe(resolve, (err) => { logger.error(err); reject(err); }); });Again I have to catch the rejected Promise and
throw an HttpExceptionto have theExceptionFiltersending a proper error response. Throwing an Error inside the Promise instead of rejecting it doesn't work)
So basically, I have 3 TryCatch Blocks for 1 Exception. This looks very verbose to me.
Is there any better way or best practice when it comes to NestJS Microservices?
Can we have an Interceptor for the rebound messages received by this.clientProxy.send and pipe it to send send the error response to the client without catching it 2 times explicitly?