001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.method.annotation; 018 019import java.lang.reflect.Method; 020import java.util.ArrayList; 021import java.util.Arrays; 022import java.util.Collections; 023import java.util.List; 024import java.util.Map; 025import java.util.concurrent.ConcurrentHashMap; 026 027import org.springframework.core.ExceptionDepthComparator; 028import org.springframework.core.MethodIntrospector; 029import org.springframework.core.annotation.AnnotationUtils; 030import org.springframework.util.ClassUtils; 031import org.springframework.util.ReflectionUtils.MethodFilter; 032import org.springframework.web.bind.annotation.ExceptionHandler; 033 034/** 035 * Discovers {@linkplain ExceptionHandler @ExceptionHandler} methods in a given class, 036 * including all of its superclasses, and helps to resolve a given {@link Exception} 037 * to the exception types supported by a given {@link Method}. 038 * 039 * @author Rossen Stoyanchev 040 * @author Juergen Hoeller 041 * @since 3.1 042 */ 043public class ExceptionHandlerMethodResolver { 044 045 /** 046 * A filter for selecting {@code @ExceptionHandler} methods. 047 */ 048 public static final MethodFilter EXCEPTION_HANDLER_METHODS = new MethodFilter() { 049 @Override 050 public boolean matches(Method method) { 051 return (AnnotationUtils.findAnnotation(method, ExceptionHandler.class) != null); 052 } 053 }; 054 055 /** 056 * Arbitrary {@link Method} reference, indicating no method found in the cache. 057 */ 058 private static final Method NO_METHOD_FOUND = ClassUtils.getMethodIfAvailable(System.class, "currentTimeMillis"); 059 060 061 private final Map<Class<? extends Throwable>, Method> mappedMethods = 062 new ConcurrentHashMap<Class<? extends Throwable>, Method>(16); 063 064 private final Map<Class<? extends Throwable>, Method> exceptionLookupCache = 065 new ConcurrentHashMap<Class<? extends Throwable>, Method>(16); 066 067 068 /** 069 * A constructor that finds {@link ExceptionHandler} methods in the given type. 070 * @param handlerType the type to introspect 071 */ 072 public ExceptionHandlerMethodResolver(Class<?> handlerType) { 073 for (Method method : MethodIntrospector.selectMethods(handlerType, EXCEPTION_HANDLER_METHODS)) { 074 for (Class<? extends Throwable> exceptionType : detectExceptionMappings(method)) { 075 addExceptionMapping(exceptionType, method); 076 } 077 } 078 } 079 080 081 /** 082 * Extract exception mappings from the {@code @ExceptionHandler} annotation first, 083 * and then as a fallback from the method signature itself. 084 */ 085 @SuppressWarnings("unchecked") 086 private List<Class<? extends Throwable>> detectExceptionMappings(Method method) { 087 List<Class<? extends Throwable>> result = new ArrayList<Class<? extends Throwable>>(); 088 detectAnnotationExceptionMappings(method, result); 089 if (result.isEmpty()) { 090 for (Class<?> paramType : method.getParameterTypes()) { 091 if (Throwable.class.isAssignableFrom(paramType)) { 092 result.add((Class<? extends Throwable>) paramType); 093 } 094 } 095 } 096 if (result.isEmpty()) { 097 throw new IllegalStateException("No exception types mapped to " + method); 098 } 099 return result; 100 } 101 102 protected void detectAnnotationExceptionMappings(Method method, List<Class<? extends Throwable>> result) { 103 ExceptionHandler ann = AnnotationUtils.findAnnotation(method, ExceptionHandler.class); 104 result.addAll(Arrays.asList(ann.value())); 105 } 106 107 private void addExceptionMapping(Class<? extends Throwable> exceptionType, Method method) { 108 Method oldMethod = this.mappedMethods.put(exceptionType, method); 109 if (oldMethod != null && !oldMethod.equals(method)) { 110 throw new IllegalStateException("Ambiguous @ExceptionHandler method mapped for [" + 111 exceptionType + "]: {" + oldMethod + ", " + method + "}"); 112 } 113 } 114 115 /** 116 * Whether the contained type has any exception mappings. 117 */ 118 public boolean hasExceptionMappings() { 119 return !this.mappedMethods.isEmpty(); 120 } 121 122 /** 123 * Find a {@link Method} to handle the given exception. 124 * Use {@link ExceptionDepthComparator} if more than one match is found. 125 * @param exception the exception 126 * @return a Method to handle the exception, or {@code null} if none found 127 */ 128 public Method resolveMethod(Exception exception) { 129 Method method = resolveMethodByExceptionType(exception.getClass()); 130 if (method == null) { 131 Throwable cause = exception.getCause(); 132 if (cause != null) { 133 method = resolveMethodByExceptionType(cause.getClass()); 134 } 135 } 136 return method; 137 } 138 139 /** 140 * Find a {@link Method} to handle the given exception type. This can be 141 * useful if an {@link Exception} instance is not available (e.g. for tools). 142 * @param exceptionType the exception type 143 * @return a Method to handle the exception, or {@code null} if none found 144 */ 145 public Method resolveMethodByExceptionType(Class<? extends Throwable> exceptionType) { 146 Method method = this.exceptionLookupCache.get(exceptionType); 147 if (method == null) { 148 method = getMappedMethod(exceptionType); 149 this.exceptionLookupCache.put(exceptionType, (method != null ? method : NO_METHOD_FOUND)); 150 } 151 return (method != NO_METHOD_FOUND ? method : null); 152 } 153 154 /** 155 * Return the {@link Method} mapped to the given exception type, or {@code null} if none. 156 */ 157 private Method getMappedMethod(Class<? extends Throwable> exceptionType) { 158 List<Class<? extends Throwable>> matches = new ArrayList<Class<? extends Throwable>>(); 159 for (Class<? extends Throwable> mappedException : this.mappedMethods.keySet()) { 160 if (mappedException.isAssignableFrom(exceptionType)) { 161 matches.add(mappedException); 162 } 163 } 164 if (!matches.isEmpty()) { 165 Collections.sort(matches, new ExceptionDepthComparator(exceptionType)); 166 return this.mappedMethods.get(matches.get(0)); 167 } 168 else { 169 return null; 170 } 171 } 172 173}