-
Notifications
You must be signed in to change notification settings - Fork 78
Closed
Labels
enhancementNew feature or requestNew feature or request
Description
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
@ExceptionHandlerconvention - Flexible return types - Handlers can return
Status,StatusException, orStatusRuntimeException - Custom metadata support - Return
StatusException/StatusRuntimeExceptionto include trailers - Most specific match - Automatically selects the most specific handler for exception hierarchies
PR: #351
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request