Skip to content

Simplify gRPC Exception Handling #350

@o-shevchenko

Description

@o-shevchenko

Simplify gRPC Exception Handling

Current Approach

Currently, to handle exceptions in gRPC services, you need to implement the GrpcExceptionHandler interface:

@Component
class MyExceptionHandler : SpringGrpcExceptionHandler {

    override fun handleException(exception: Throwable): StatusException =
        mapToStatus(exception).asException()

    private fun mapToStatus(ex: Throwable): Status = when (ex) {
        is TimeoutException -> Status.DEADLINE_EXCEEDED.withDescription(ex.message).withCause(ex)
        is IllegalArgumentException -> Status.INVALID_ARGUMENT.withDescription(ex.message).withCause(ex)
        is NotFoundException -> Status.NOT_FOUND.withDescription(ex.message).withCause(ex)
        // ... more cases
        else -> Status.UNKNOWN.withDescription(ex.message).withCause(ex)
    }
}

Proposed Solution

Introduce @GrpcAdvice and @GrpcExceptionHandler annotations (similar to Spring MVC's @ControllerAdvice and @ExceptionHandler):

@GrpcAdvice
class MyExceptionHandler {

    @GrpcExceptionHandler
    fun handleTimeoutException(ex: TimeoutException): Status =
        Status.DEADLINE_EXCEEDED.withDescription(ex.message).withCause(ex)

    @GrpcExceptionHandler
    fun handleIllegalArgument(ex: IllegalArgumentException): Status =
        Status.INVALID_ARGUMENT.withDescription(ex.message).withCause(ex)

    @GrpcExceptionHandler
    fun handleNotFound(ex: NotFoundException): Status =
        Status.NOT_FOUND.withDescription(ex.message).withCause(ex)
}

Benefits

  • Cleaner code - Each exception type has its own dedicated handler method
  • Familiar pattern - Follows Spring MVC's @ExceptionHandler convention
  • Flexible return types - Handlers can return Status, StatusException, or StatusRuntimeException
  • Custom metadata support - Return StatusException/StatusRuntimeException to include trailers
  • Most specific match - Automatically selects the most specific handler for exception hierarchies

Example: https://github.com/grpc-ecosystem/grpc-spring/blob/master/grpc-server-spring-boot-starter/src/main/java/net/devh/boot/grpc/server/advice/GrpcExceptionHandler.java#L69

PR: #351

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions