Skip to main content

Exception Handling

Provides spring-web like experience for gRPC server exception handling.

@GrpcExceptionHandler

@GrpcExceptionHandler is used to define a method that handles exceptions, it's similar to @ExceptionHandler in Spring Web, and it must be worked with @GrpcAdvice.

@GrpcAdvice
public class ExceptionAdvice {
@GrpcExceptionHandler(IllegalArgumentException.class)
public StatusRuntimeException handleRuntimeException(IllegalArgumentException e, Metadata headers) { // You can inject request Metadata
return Status.INTERNAL.withDescription(e.getMessage()).asRuntimeException();
}
}

Method annotated with @GrpcExceptionHandler must return one of the following types:

  • io.grpc.Status
  • io.grpc.StatusException
  • io.grpc.StatusRuntimeException
  • Throwable

GrpcExceptionResolver

GrpcExceptionResolver is used to resolve exceptions thrown by gRPC services.

Implement GrpcExceptionResolver to process IllegalArgumentException:

@Bean
public class IllegalArgumentExceptionResolver implements GrpcExceptionResolver {
@Override
public StatusRuntimeException resolve(Throwable throwable, ServerCall<?, ?> call, Metadata headers) {
if (throwable instanceof IllegalArgumentException e) {
return new StatusRuntimeException(Status.INVALID_ARGUMENT.withDescription(e.getMessage()));
}
return null;
}
}

GrpcUnhandledExceptionProcessor

GrpcUnhandledExceptionProcessor is used to process unhandled exceptions, which are not resolved by GrpcExceptionResolver.

This interface is generally used for exception reporting.

Send exception to Sentry when unhandled exception occurs:

@Bean
public class SentryExceptionReporter implements GrpcUnhandledExceptionProcessor {
@Override
public void process(Throwable throwable, ServerCall<?, ?> call, Metadata headers) {
Sentry.captureException(throwable);
}
}