|
| 1 | +/* |
| 2 | + * Copyright 2024-present the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.grpc.server.advice; |
| 18 | + |
| 19 | +import java.lang.reflect.InvocationTargetException; |
| 20 | +import java.lang.reflect.Method; |
| 21 | +import java.lang.reflect.Parameter; |
| 22 | +import java.lang.reflect.Type; |
| 23 | +import java.util.Map.Entry; |
| 24 | + |
| 25 | +import org.apache.commons.logging.Log; |
| 26 | +import org.apache.commons.logging.LogFactory; |
| 27 | +import org.jspecify.annotations.Nullable; |
| 28 | + |
| 29 | +import org.springframework.util.Assert; |
| 30 | + |
| 31 | +import io.grpc.Metadata; |
| 32 | +import io.grpc.Status; |
| 33 | +import io.grpc.StatusException; |
| 34 | +import io.grpc.StatusRuntimeException; |
| 35 | + |
| 36 | +/** |
| 37 | + * Handles exceptions by delegating to {@link GrpcExceptionHandler @GrpcExceptionHandler} |
| 38 | + * methods in {@link GrpcAdvice @GrpcAdvice} beans. |
| 39 | + * |
| 40 | + * @author Oleksandr Shevchenko |
| 41 | + * @see GrpcAdvice |
| 42 | + * @see GrpcExceptionHandler |
| 43 | + */ |
| 44 | +public class GrpcAdviceExceptionHandler implements org.springframework.grpc.server.exception.GrpcExceptionHandler { |
| 45 | + |
| 46 | + private static final Log logger = LogFactory.getLog(GrpcAdviceExceptionHandler.class); |
| 47 | + |
| 48 | + private final GrpcExceptionHandlerMethodResolver grpcExceptionHandlerMethodResolver; |
| 49 | + |
| 50 | + /** |
| 51 | + * Create a new instance. |
| 52 | + * @param grpcExceptionHandlerMethodResolver the method resolver to use |
| 53 | + */ |
| 54 | + public GrpcAdviceExceptionHandler(GrpcExceptionHandlerMethodResolver grpcExceptionHandlerMethodResolver) { |
| 55 | + Assert.notNull(grpcExceptionHandlerMethodResolver, "grpcExceptionHandlerMethodResolver must not be null"); |
| 56 | + this.grpcExceptionHandlerMethodResolver = grpcExceptionHandlerMethodResolver; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public @Nullable StatusException handleException(Throwable exception) { |
| 61 | + try { |
| 62 | + Object mappedReturnType = handleThrownException(exception); |
| 63 | + if (mappedReturnType == null) { |
| 64 | + return null; |
| 65 | + } |
| 66 | + Status status = resolveStatus(mappedReturnType); |
| 67 | + Metadata metadata = resolveMetadata(mappedReturnType); |
| 68 | + return status.asException(metadata); |
| 69 | + } |
| 70 | + catch (Throwable errorWhileResolving) { |
| 71 | + if (errorWhileResolving != exception) { |
| 72 | + errorWhileResolving.addSuppressed(exception); |
| 73 | + } |
| 74 | + logger.error("Exception thrown during invocation of annotated @GrpcExceptionHandler method: ", |
| 75 | + errorWhileResolving); |
| 76 | + return Status.INTERNAL.withCause(errorWhileResolving) |
| 77 | + .withDescription("There was a server error trying to handle an exception") |
| 78 | + .asException(); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Resolve the gRPC status from the handler's return value. |
| 84 | + * @param mappedReturnType the handler return value |
| 85 | + * @return the resolved status |
| 86 | + */ |
| 87 | + protected Status resolveStatus(Object mappedReturnType) { |
| 88 | + if (mappedReturnType instanceof Status status) { |
| 89 | + return status; |
| 90 | + } |
| 91 | + else if (mappedReturnType instanceof Throwable throwable) { |
| 92 | + return Status.fromThrowable(throwable); |
| 93 | + } |
| 94 | + throw new IllegalStateException( |
| 95 | + String.format("Error for mapped return type [%s] inside @GrpcAdvice, it has to be of type: " |
| 96 | + + "[Status, StatusException, StatusRuntimeException, Throwable]", mappedReturnType)); |
| 97 | + } |
| 98 | + |
| 99 | + /** |
| 100 | + * Resolve the metadata from the handler's return value. |
| 101 | + * @param mappedReturnType the handler return value |
| 102 | + * @return the resolved metadata, or empty metadata |
| 103 | + */ |
| 104 | + protected Metadata resolveMetadata(Object mappedReturnType) { |
| 105 | + Metadata result = null; |
| 106 | + if (mappedReturnType instanceof StatusException statusException) { |
| 107 | + result = statusException.getTrailers(); |
| 108 | + } |
| 109 | + else if (mappedReturnType instanceof StatusRuntimeException statusRuntimeException) { |
| 110 | + result = statusRuntimeException.getTrailers(); |
| 111 | + } |
| 112 | + return (result == null) ? new Metadata() : result; |
| 113 | + } |
| 114 | + |
| 115 | + /** |
| 116 | + * Look up and invoke the handler method for the given exception. |
| 117 | + * @param exception the exception to handle |
| 118 | + * @return the handler result, or {@code null} if no handler is mapped |
| 119 | + * @throws Throwable if the handler throws an exception |
| 120 | + */ |
| 121 | + @Nullable |
| 122 | + protected Object handleThrownException(Throwable exception) throws Throwable { |
| 123 | + if (logger.isDebugEnabled()) { |
| 124 | + logger.debug("Exception caught during gRPC execution: " + exception); |
| 125 | + } |
| 126 | + |
| 127 | + Class<? extends Throwable> exceptionClass = exception.getClass(); |
| 128 | + boolean exceptionIsMapped = this.grpcExceptionHandlerMethodResolver.isMethodMappedForException(exceptionClass); |
| 129 | + if (!exceptionIsMapped) { |
| 130 | + return null; |
| 131 | + } |
| 132 | + |
| 133 | + Entry<Object, Method> methodWithInstance = this.grpcExceptionHandlerMethodResolver |
| 134 | + .resolveMethodWithInstance(exceptionClass); |
| 135 | + Method mappedMethod = methodWithInstance.getValue(); |
| 136 | + Object instanceOfMappedMethod = methodWithInstance.getKey(); |
| 137 | + |
| 138 | + if (mappedMethod == null || instanceOfMappedMethod == null) { |
| 139 | + return null; |
| 140 | + } |
| 141 | + |
| 142 | + Object[] instancedParams = determineInstancedParameters(mappedMethod, exception); |
| 143 | + return invokeMappedMethodSafely(mappedMethod, instanceOfMappedMethod, instancedParams); |
| 144 | + } |
| 145 | + |
| 146 | + private Object[] determineInstancedParameters(Method mappedMethod, Throwable exception) { |
| 147 | + Parameter[] parameters = mappedMethod.getParameters(); |
| 148 | + Object[] instancedParams = new Object[parameters.length]; |
| 149 | + |
| 150 | + for (int i = 0; i < parameters.length; i++) { |
| 151 | + Class<?> parameterClass = convertToClass(parameters[i]); |
| 152 | + if (parameterClass.isAssignableFrom(exception.getClass())) { |
| 153 | + instancedParams[i] = exception; |
| 154 | + break; |
| 155 | + } |
| 156 | + } |
| 157 | + return instancedParams; |
| 158 | + } |
| 159 | + |
| 160 | + private Class<?> convertToClass(Parameter parameter) { |
| 161 | + Type paramType = parameter.getParameterizedType(); |
| 162 | + if (paramType instanceof Class<?> clazz) { |
| 163 | + return clazz; |
| 164 | + } |
| 165 | + throw new IllegalStateException("Parameter type of method has to be from Class, it was: " + paramType); |
| 166 | + } |
| 167 | + |
| 168 | + private Object invokeMappedMethodSafely(Method mappedMethod, Object instanceOfMappedMethod, |
| 169 | + Object[] instancedParams) throws Throwable { |
| 170 | + try { |
| 171 | + return mappedMethod.invoke(instanceOfMappedMethod, instancedParams); |
| 172 | + } |
| 173 | + catch (InvocationTargetException ex) { |
| 174 | + throw ex.getCause(); |
| 175 | + } |
| 176 | + catch (IllegalAccessException ex) { |
| 177 | + throw new IllegalStateException("Could not access @GrpcExceptionHandler method: " + mappedMethod, ex); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | +} |
0 commit comments