简体   繁体   中英

NestJS - Microservices - Kafka Exception Handling

I'm using NestJS to implement a microservice architecture, I'm using CLIENT app using NestJS,

The client app receives a rest request and sends to Kafka to get the result

  try {
     const pattern = 'findDoctors';
     const payload = body;
     const doctors = await lastValueFrom(
       this.client.send(pattern, payload).pipe(timeout(50000)),
     );
     return doctors;
   } catch (e) {
     console.log(e);
     throw new Error(e);
   }

And in the microservice side (Hybrid Application for now, will remove the rest apis later)

 @MessagePattern('findDoctors')
 findDoctors(@Payload() message): any {
   return this.doctorService.searchForDoctors(message.value);
 }
async searchForDoctors(data): Promise<any[]> {
   this.logger.info('Started search for doctors job');
   throw 'Not Found';
}

After i throw the exception i get in the logs

node:17720) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object
   at Function.from (buffer.js:330:9)
   at ServerKafka.assignErrorHeader (C:\Users\Desktop\Projects\node_modules\@nestjs\microservices\server\server-kafka.js:137:73)
   at ServerKafka.sendMessage (C:\Users\Desktop\Projects\node_modules\@nestjs\microservices\server\server-kafka.js:119:14)
   at C:\Users\Desktop\Projects\node_modules\@nestjs\microservices\server\server-kafka.js:81:31
   at C:\Users\Desktop\node_modules\@nestjs\microservices\server\server.js:46:31
   at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:17720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:17720) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

and the client side just waits to timeout and never receive an exception response from the micro service

Tried using RpcException but it's the same

Found the answer

used

return new RpcException('not found');

instead of

throw new RpcException('not found')

throwing the exception needs an exception filter to catch it

@Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
  catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
    return throwError(exception.getError());  
  }
}

and in the client side you can catch the error when using filters and return a normal http exception, or use filters on that too

 @Post('/search')
  async findAll(@Body() body) {
    console.log('Sending kafka msg');
    try {
      const doctors = await this.doctorService.findDoctors(body);
      return doctors;
    } catch (e) {
      console.log(e)
      throw new HttpException({
        status: '500',
        error: e.message,
      }, 500)
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM