Skip to the content.

Exception Handling inside GrpcService

<- Back to Index

This section describes how you can handle exceptions inside GrpcService layer without cluttering up your code.

Table of Contents

Additional Topics

Proper exception handling

If you are already familiar with spring’s error handling, you should see some similarities with the exception handling for gRPC.

An explanation for the following class:

@GrpcAdvice
public class GrpcExceptionAdvice {


    @GrpcExceptionHandler
    public Status handleInvalidArgument(IllegalArgumentException e) {
        return Status.INVALID_ARGUMENT.withDescription("Your description").withCause(e);
    }

    @GrpcExceptionHandler(ResourceNotFoundException.class)
    public StatusException handleResourceNotFoundException(ResourceNotFoundException e) {
        Status status = Status.NOT_FOUND.withDescription("Your description").withCause(e);
        Metadata metadata = ...
        return status.asException(metadata);
    }

}

Note: Cause is not transmitted from server to client - as stated in official docs So we recommend adding it to the Status/StatusException to avoid the loss of information on the server side.

Detailed explanation

Priority of mapped exceptions

Given this method with specified exception in the annotation and as a method argument

@GrpcExceptionHandler(ResourceNotFoundException.class)
public StatusException handleResourceNotFoundException(ResourceNotFoundException e) {
    // your exception handling
}

If the GrpcExceptionHandler annotation contains at least one exception type, then only those will be considered for exception handling for that method. The method parameters must be “compatible” with the specified exception types. If the annotation does not specify any handled exception types, then all method parameters are being used instead.

(“Compatible” means that the exception type in annotation is either the same class or a superclass of one of the listed method parameters)

Sending Metadata in response

In case you want to send metadata in your exception response, let’s have a look at the following example.

@GrpcExceptionHandler
public StatusRuntimeException handleResourceNotFoundException(IllegalArgumentException e) {
    Status status = Status.INVALID_ARGUMENT.withDescription("Your description");
    Metadata metadata = ...
    return status.asRuntimeException(metadata);
}

If you do not need Metadata in your response, just return your specified Status.

Overview of returnable types

Here is a small overview of possible mapped return types with @GrpcExceptionHandler and if custom Metadata can be returned:

Return Type Supports Custom Metadata
Status &cross;
StatusException
StatusRuntimeException

Additional Topics


<- Back to Index