Search Tutorials


Spring Boot + gRPC Error Handling Hello World Example | JavaInUse

Spring Boot + gRPC Error Handling Example

In this tutorial we will be looking at gRPC Error Handling Hello World Example. In the next tutorial we will be further modifying this example to implement Error Handling using gRPC Trailer Metadata. Also in another tutorial we will be implementing Global Exception Handler Using GrpcAdvice.
Error handling in gRPC client and server involves managing and reacting to errors that may occur during communication between the client and server. In gRPC, there are different types of errors that can occur, such as network errors, server errors, security errors, and protocol errors.
In gRPC, error handling is typically implemented using gRPC status codes and status messages. When an error occurs, the server will send an appropriate status code and message to the client, which can then handle the error accordingly.
In the client, error handling can involve checking the status code of the response and taking appropriate action, such as retrying the request, logging the error, or displaying an error message to the user.
gRPC provides users with well defined status codes as part of the RPC API that can be made use of during error handling.
Code Number
OK 0
CANCELLED 1
UNKNOWN 2
INVALID_ARGUMENT 3
DEADLINE_EXCEEDED 4
NOT_FOUND 5
ALREADY_EXISTS 6
PERMISSION_DENIED 7
RESOURCE_EXHAUSTED 8
FAILED_PRECONDITION 9
ABORTED 10
OUT_OF_RANGE 11
UNIMPLEMENTED 12
INTERNAL 13
UNAVAILABLE 14
DATA_LOSS 15
UNAUTHENTICATED 16

Video

This tutorial is explained in the below Youtube Video.

gRPC - Table of Contents

Spring Boot+ gRPC Hello World Example Spring Boot gRPC Server + C# gRPC Client Example Spring Boot 3 + gRPC - Types of gRPC Spring Boot 3 + gRPC Unary Example Spring Boot 3 + gRPC Server Streaming Example Spring Boot 3 + gRPC Client Streaming Example Spring Boot 3 + gRPC Bidirectional Streaming Example Spring Boot + gRPC Deadline Example Spring Boot + gRPC Error Handling Example Spring Boot + gRPC Error Handling - Using Trailer Metadata Spring Boot + gRPC Error Handling - Global Exception Handler Using GrpcAdvice

Implementation

We will be modifying the code we implemented in a previous tutorial - Spring Boot 3 + gRPC Unary Example. We will be implementing error handling code to return the gRPC status code and the description from the gRPC server to the client.
Spring Boot 3 + gRPC server error handling

To the BankAccountBalanceService we will be adding a conditional statement that checks if the account number retrieved from a request is equal to "account5". If the condition is true, it means that the requested account number cannot be found. In this case, the code generates an error response with the status "NOT_FOUND" and a description stating that the requested account number cannot be found. The error response is then returned to the caller, effectively informing them that the requested account number does not exist.
package com.javainuse.bank.service;

import com.javainuse.banking.AccountBalanceResponse;
import com.javainuse.banking.AccountBalanceServiceGrpc;
import com.javainuse.banking.AccountRequest;

import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
public class BankAccountBalanceService extends AccountBalanceServiceGrpc.AccountBalanceServiceImplBase {

	@Override
	public void getAccountBalance(AccountRequest request,
			StreamObserver<com.javainuse.banking.AccountBalanceResponse> responseObserver) {

		if ((request.getAccountNumber().equals("account5"))) {
			responseObserver.onError((Status.NOT_FOUND.withDescription("The requested Account Number cannot be found."))
					.asRuntimeException());
			return;
		}
		AccountBalanceResponse empResp = AccountBalanceResponse.newBuilder()
				.setAccountNumber(request.getAccountNumber()).setBalance(100).build();

		// set the response object
		responseObserver.onNext(empResp);

		// mark process is completed
		responseObserver.onCompleted();
	}
}
Start the gRPC server.





Spring Boot 3 + gRPC server
Now run the gRPC client by passing the account number as "account5". We get the following exception at the client end.
Spring Boot 3 + gRPC client exception
So this needs to be properly handled at the gRPC client side by writing the gRPC server call inside the try catch block.
package com.javainuse.bank.service;

import org.springframework.stereotype.Service;

import com.javainuse.banking.AccountBalanceResponse;
import com.javainuse.banking.AccountBalanceServiceGrpc;
import com.javainuse.banking.AccountRequest;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

@Service
public class BankService {

	public void getAccountBalance() {

		ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8090).usePlaintext().build();

		AccountBalanceServiceGrpc.AccountBalanceServiceBlockingStub stub = AccountBalanceServiceGrpc
				.newBlockingStub(channel);

		try {
			AccountBalanceResponse bookResponse = stub
					.getAccountBalance(AccountRequest.newBuilder().setAccountNumber("account5").build());

			System.out.println(bookResponse);
		} catch (StatusRuntimeException ex) {
			Status status = ex.getStatus();
			System.out.println("error code -" + status.getCode());
			System.out.println("error description -" + status.getDescription());
		}

		channel.shutdown();

	}
}
If we now run the client again we can see that the client has gracefully handled the exception.
Spring Boot 3 + gRPC client exception handled

Download Source Code

Download it - Spring Boot + gRPC Error Handling Client Example
Download it - Spring Boot + gRPC Error Handling Server Example