DEV Community

Mohsen Bostan
Mohsen Bostan

Posted on

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.ts

export 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 {}
Enter fullscreen mode Exit fullscreen mode

Add the client interceptor to your client:

import { GrpcToHttpInterceptor } from 'nestjs-grpc-exceptions';

@Get(':id')
@UseInterceptors(GrpcToHttpInterceptor)
function findUser(@Param('id') id: number): void;
Enter fullscreen mode Exit fullscreen mode

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.");
Enter fullscreen mode Exit fullscreen mode

And that is all you need.

Useful links:

Wish you bugless codes! ❤️

Top comments (0)