Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 21, 2023 09:27 pm GMT

How to handle gRPC errors in NestJS

NestJS has a great way of creating microservices specially when it comes to gRPC! You can easily use gRPC in your NestJS applications without doing extra work.

Error Handling: The Basic Solution

Handling errors correctly in microservices is really important. NestJS provides RpcException for this. Let's take a look at some code:

// user-service/src/find-user.query.tsexport class FindUserQuery implements IQuery {    async execute(params: FindUserQueryParam): Observable<User> {        const user = await this.repository.findOne({ id: params.id });        if(!user) {            throw new RpcException("User Not Found.");        }        return of(user);    }}

This example code shows how to throw exceptions that are microservice related. Although this works fine but there is a problem! If you want to send a HTTP error this will not help because you actually don't know what type of error this is.

We all know that 404 is a Not Found error but gRPC uses 5 for that. On the other hand since the RpcException Isn't only for gRPC (You can use this exception regardless of the transport method which you use), The client side wouldn't know that this is a code 5 error.

Efficient gRPC Error Handling

To solve the explained problem, you have to pass an object containing the gRPC error code. But let me save you!

I have published a library that provides some wrappers for the RpcException. It includes almost all commonly used gRPC error codes. The library provides 2 main features:

  • Exception classes similar to NestJS built-in HttpExecptions
  • Automatic conversion of gRPC error from your microservice servers to HttpException in the client

How To Use The Library?

First install the library with any package manager you prefer.

npm i nestjs-grpc-exceptions

Then add the GrpcServerExceptionFilter to your gRPC server:

import { Module } from "@nestjs/common";import { APP_FILTER } from "@nestjs/core";import { GrpcServerExceptionFilter } from "nestjs-grpc-exceptions";@Module({  providers: [    {      provide: APP_FILTER,      useClass: GrpcServerExceptionFilter,    },  ],})export class UserModule {}

Add the client interceptor to your client:

import { GrpcToHttpInterceptor } from 'nestjs-grpc-exceptions';@Get(':id')@UseInterceptors(GrpcToHttpInterceptor)function findUser(@Param('id') id: number): void;

Now you can use the exception classes in your servers:

import {  GrpcNotFoundException,  GrpcInvalidArgumentException,} from "nestjs-grpc-exceptions";throw new GrpcNotFoundException("User Not Found.");throw new GrpcInvalidArgumentException("input 'name' is not valid.");

And that is all you need.

Useful links:

Wish you bugless codes!


Original Link: https://dev.to/mohsenbostan/how-to-handle-grpc-errors-in-nestjs-22jc

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To