AnnotationMethodHandlerExceptionResolver.java 17.6 KB
Newer Older
1
/*
2
 * Copyright 2002-2015 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.annotation;

19
import java.io.IOException;
20 21 22 23 24 25 26 27 28 29
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
30
import java.util.HashMap;
31 32 33
import java.util.List;
import java.util.Locale;
import java.util.Map;
C
Costin Leau 已提交
34
import java.util.concurrent.ConcurrentHashMap;
35
import javax.servlet.ServletException;
36 37 38 39 40
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
P
Phillip Webb 已提交
41
import javax.xml.transform.Source;
42

43
import org.springframework.core.ExceptionDepthComparator;
44 45
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.MethodParameter;
46
import org.springframework.core.annotation.AnnotatedElementUtils;
47
import org.springframework.core.annotation.AnnotationUtils;
48
import org.springframework.core.annotation.SynthesizingMethodParameter;
49 50
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
51
import org.springframework.http.HttpStatus;
J
Juergen Hoeller 已提交
52
import org.springframework.http.MediaType;
53 54 55 56 57 58
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.xml.SourceHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
59 60 61 62
import org.springframework.ui.Model;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
63
import org.springframework.util.StringUtils;
64
import org.springframework.web.bind.annotation.ExceptionHandler;
65
import org.springframework.web.bind.annotation.ResponseBody;
66
import org.springframework.web.bind.annotation.ResponseStatus;
67 68 69 70 71 72 73 74 75 76 77
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
 * Implementation of the {@link org.springframework.web.servlet.HandlerExceptionResolver} interface that handles
78 79 80
 * exceptions through the {@link ExceptionHandler} annotation.
 *
 * <p>This exception resolver is enabled by default in the {@link org.springframework.web.servlet.DispatcherServlet}.
81 82
 *
 * @author Arjen Poutsma
83
 * @author Juergen Hoeller
84
 * @since 3.0
85
 * @deprecated as of Spring 3.2, in favor of
86
 * {@link org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver ExceptionHandlerExceptionResolver}
87
 */
88
@Deprecated
89 90
public class AnnotationMethodHandlerExceptionResolver extends AbstractHandlerExceptionResolver {

C
Costin Leau 已提交
91
	// dummy method placeholder
92 93 94
	private static final Method NO_METHOD_FOUND = ClassUtils.getMethodIfAvailable(System.class, "currentTimeMillis", (Class<?>[]) null);

	private final Map<Class<?>, Map<Class<? extends Throwable>, Method>> exceptionHandlerCache =
95
			new ConcurrentHashMap<Class<?>, Map<Class<? extends Throwable>, Method>>(64);
C
Costin Leau 已提交
96

97 98
	private WebArgumentResolver[] customArgumentResolvers;

99
	private HttpMessageConverter<?>[] messageConverters =
P
Phillip Webb 已提交
100 101 102
			new HttpMessageConverter<?>[] {new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(),
			new SourceHttpMessageConverter<Source>(),
			new org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter()};
103 104


105
	/**
J
Juergen Hoeller 已提交
106 107 108
	 * Set a custom ArgumentResolvers to use for special method parameter types.
	 * <p>Such a custom ArgumentResolver will kick in first, having a chance to resolve
	 * an argument value before the standard argument handling kicks in.
109 110 111 112 113 114
	 */
	public void setCustomArgumentResolver(WebArgumentResolver argumentResolver) {
		this.customArgumentResolvers = new WebArgumentResolver[]{argumentResolver};
	}

	/**
J
Juergen Hoeller 已提交
115 116 117
	 * Set one or more custom ArgumentResolvers to use for special method parameter types.
	 * <p>Any such custom ArgumentResolver will kick in first, having a chance to resolve
	 * an argument value before the standard argument handling kicks in.
118 119 120 121 122
	 */
	public void setCustomArgumentResolvers(WebArgumentResolver[] argumentResolvers) {
		this.customArgumentResolvers = argumentResolvers;
	}

123 124 125 126 127 128 129 130
	/**
	 * Set the message body converters to use.
	 * <p>These converters are used to convert from and to HTTP requests and responses.
	 */
	public void setMessageConverters(HttpMessageConverter<?>[] messageConverters) {
		this.messageConverters = messageConverters;
	}

131

132
	@Override
133 134
	protected ModelAndView doResolveException(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
135

136 137 138
		if (handler != null) {
			Method handlerMethod = findBestExceptionHandlerMethod(handler, ex);
			if (handlerMethod != null) {
139
				ServletWebRequest webRequest = new ServletWebRequest(request, response);
140 141 142 143 144 145
				try {
					Object[] args = resolveHandlerArguments(handlerMethod, handler, webRequest, ex);
					if (logger.isDebugEnabled()) {
						logger.debug("Invoking request handler method: " + handlerMethod);
					}
					Object retVal = doInvokeMethod(handlerMethod, handler, args);
146
					return getModelAndView(handlerMethod, retVal, webRequest);
147 148 149 150 151 152 153 154 155 156 157
				}
				catch (Exception invocationEx) {
					logger.error("Invoking request method resulted in exception : " + handlerMethod, invocationEx);
				}
			}
		}
		return null;
	}

	/**
	 * Finds the handler method that matches the thrown exception best.
158
	 * @param handler the handler object
159
	 * @param thrownException the exception to be handled
160
	 * @return the best matching method; or {@code null} if none is found
161 162
	 */
	private Method findBestExceptionHandlerMethod(Object handler, final Exception thrownException) {
C
Costin Leau 已提交
163
		final Class<?> handlerType = ClassUtils.getUserClass(handler);
164
		final Class<? extends Throwable> thrownExceptionType = thrownException.getClass();
C
Costin Leau 已提交
165
		Method handlerMethod = null;
166

167
		Map<Class<? extends Throwable>, Method> handlers = this.exceptionHandlerCache.get(handlerType);
C
Costin Leau 已提交
168 169 170 171 172 173 174
		if (handlers != null) {
			handlerMethod = handlers.get(thrownExceptionType);
			if (handlerMethod != null) {
				return (handlerMethod == NO_METHOD_FOUND ? null : handlerMethod);
			}
		}
		else {
175 176
			handlers = new ConcurrentHashMap<Class<? extends Throwable>, Method>(16);
			this.exceptionHandlerCache.put(handlerType, handlers);
C
Costin Leau 已提交
177
		}
178

179
		final Map<Class<? extends Throwable>, Method> matchedHandlers = new HashMap<Class<? extends Throwable>, Method>();
180 181

		ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() {
182
			@Override
183 184 185 186 187
			public void doWith(Method method) {
				method = ClassUtils.getMostSpecificMethod(method, handlerType);
				List<Class<? extends Throwable>> handledExceptions = getHandledExceptions(method);
				for (Class<? extends Throwable> handledException : handledExceptions) {
					if (handledException.isAssignableFrom(thrownExceptionType)) {
188 189
						if (!matchedHandlers.containsKey(handledException)) {
							matchedHandlers.put(handledException, method);
190 191
						}
						else {
192
							Method oldMappedMethod = matchedHandlers.get(handledException);
193 194 195 196 197
							if (!oldMappedMethod.equals(method)) {
								throw new IllegalStateException(
										"Ambiguous exception handler mapped for " + handledException + "]: {" +
												oldMappedMethod + ", " + method + "}.");
							}
198 199 200 201 202
						}
					}
				}
			}
		});
203

204
		handlerMethod = getBestMatchingMethod(matchedHandlers, thrownException);
C
Costin Leau 已提交
205 206
		handlers.put(thrownExceptionType, (handlerMethod == null ? NO_METHOD_FOUND : handlerMethod));
		return handlerMethod;
207 208 209
	}

	/**
210
	 * Returns all the exception classes handled by the given method.
211
	 * <p>The default implementation looks for exceptions in the annotation,
212 213
	 * or - if that annotation element is empty - any exceptions listed in the method parameters if the method
	 * is annotated with {@code @ExceptionHandler}.
214 215 216 217 218 219
	 * @param method the method
	 * @return the handled exceptions
	 */
	@SuppressWarnings("unchecked")
	protected List<Class<? extends Throwable>> getHandledExceptions(Method method) {
		List<Class<? extends Throwable>> result = new ArrayList<Class<? extends Throwable>>();
220
		ExceptionHandler exceptionHandler = AnnotationUtils.findAnnotation(method, ExceptionHandler.class);
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
		if (exceptionHandler != null) {
			if (!ObjectUtils.isEmpty(exceptionHandler.value())) {
				result.addAll(Arrays.asList(exceptionHandler.value()));
			}
			else {
				for (Class<?> param : method.getParameterTypes()) {
					if (Throwable.class.isAssignableFrom(param)) {
						result.add((Class<? extends Throwable>) param);
					}
				}
			}
		}
		return result;
	}

236
	/**
237 238
	 * Uses the {@link DepthComparator} to find the best matching method
	 * @return the best matching method or {@code null}.
239
	 */
240 241
	private Method getBestMatchingMethod(
			Map<Class<? extends Throwable>, Method> resolverMethods, Exception thrownException) {
242

243
		if (resolverMethods.isEmpty()) {
244 245
			return null;
		}
246 247 248 249
		Class<? extends Throwable> closestMatch =
				ExceptionDepthComparator.findClosestMatch(resolverMethods.keySet(), thrownException);
		Method method = resolverMethods.get(closestMatch);
		return ((method == null) || (NO_METHOD_FOUND == method)) ? null : method;
250 251
	}

252 253 254 255 256
	/**
	 * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}.
	 */
	private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
			NativeWebRequest webRequest, Exception thrownException) throws Exception {
257

258
		Class<?>[] paramTypes = handlerMethod.getParameterTypes();
259 260 261
		Object[] args = new Object[paramTypes.length];
		Class<?> handlerType = handler.getClass();
		for (int i = 0; i < args.length; i++) {
262
			MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i);
263
			GenericTypeResolver.resolveParameterType(methodParam, handlerType);
264
			Class<?> paramType = methodParam.getParameterType();
265 266 267 268 269
			Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException);
			if (argValue != WebArgumentResolver.UNRESOLVED) {
				args[i] = argValue;
			}
			else {
270 271
				throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
						"] for @ExceptionHandler method: " + handlerMethod);
272 273 274 275 276 277
			}
		}
		return args;
	}

	/**
278 279
	 * Resolves common method arguments. Delegates to registered {@link #setCustomArgumentResolver(WebArgumentResolver)
	 * argumentResolvers} first, then checking {@link #resolveStandardArgument}.
280
	 * @param methodParameter the method parameter
281
	 * @param webRequest the request
282 283 284
	 * @param thrownException the exception thrown
	 * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED}
	 */
285
	protected Object resolveCommonArgument(MethodParameter methodParameter, NativeWebRequest webRequest,
286
			Exception thrownException) throws Exception {
287

288 289 290 291 292 293 294 295 296 297 298
		// Invoke custom argument resolvers if present...
		if (this.customArgumentResolvers != null) {
			for (WebArgumentResolver argumentResolver : this.customArgumentResolvers) {
				Object value = argumentResolver.resolveArgument(methodParameter, webRequest);
				if (value != WebArgumentResolver.UNRESOLVED) {
					return value;
				}
			}
		}

		// Resolution of standard parameter types...
299
		Class<?> paramType = methodParameter.getParameterType();
300 301 302 303 304 305 306 307 308 309 310
		Object value = resolveStandardArgument(paramType, webRequest, thrownException);
		if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) {
			throw new IllegalStateException(
					"Standard argument type [" + paramType.getName() + "] resolved to incompatible value of type [" +
							(value != null ? value.getClass() : null) +
							"]. Consider declaring the argument type in a less specific fashion.");
		}
		return value;
	}

	/**
311 312 313 314
	 * Resolves standard method arguments. The default implementation handles {@link NativeWebRequest},
	 * {@link ServletRequest}, {@link ServletResponse}, {@link HttpSession}, {@link Principal},
	 * {@link Locale}, request {@link InputStream}, request {@link Reader}, response {@link OutputStream},
	 * response {@link Writer}, and the given {@code thrownException}.
315 316
	 * @param parameterType the method parameter type
	 * @param webRequest the request
317 318 319
	 * @param thrownException the exception thrown
	 * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED}
	 */
320
	protected Object resolveStandardArgument(Class<?> parameterType, NativeWebRequest webRequest,
321
			Exception thrownException) throws Exception {
322

J
Juergen Hoeller 已提交
323 324 325 326
		if (parameterType.isInstance(thrownException)) {
			return thrownException;
		}
		else if (WebRequest.class.isAssignableFrom(parameterType)) {
327 328 329
			return webRequest;
		}

330 331
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
332 333 334 335 336 337 338 339 340 341 342 343 344

		if (ServletRequest.class.isAssignableFrom(parameterType)) {
			return request;
		}
		else if (ServletResponse.class.isAssignableFrom(parameterType)) {
			return response;
		}
		else if (HttpSession.class.isAssignableFrom(parameterType)) {
			return request.getSession();
		}
		else if (Principal.class.isAssignableFrom(parameterType)) {
			return request.getUserPrincipal();
		}
345
		else if (Locale.class == parameterType) {
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
			return RequestContextUtils.getLocale(request);
		}
		else if (InputStream.class.isAssignableFrom(parameterType)) {
			return request.getInputStream();
		}
		else if (Reader.class.isAssignableFrom(parameterType)) {
			return request.getReader();
		}
		else if (OutputStream.class.isAssignableFrom(parameterType)) {
			return response.getOutputStream();
		}
		else if (Writer.class.isAssignableFrom(parameterType)) {
			return response.getWriter();
		}
		else {
			return WebArgumentResolver.UNRESOLVED;

		}
	}

	private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception {
		ReflectionUtils.makeAccessible(method);
		try {
			return method.invoke(target, args);
		}
		catch (InvocationTargetException ex) {
			ReflectionUtils.rethrowException(ex.getTargetException());
		}
		throw new IllegalStateException("Should never get here");
	}

	@SuppressWarnings("unchecked")
378 379
	private ModelAndView getModelAndView(Method handlerMethod, Object returnValue, ServletWebRequest webRequest)
			throws Exception {
380

381 382 383 384
		ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(handlerMethod, ResponseStatus.class);
		if (responseStatus != null) {
			HttpStatus statusCode = responseStatus.code();
			String reason = responseStatus.reason();
385
			if (!StringUtils.hasText(reason)) {
386
				webRequest.getResponse().setStatus(statusCode.value());
387 388
			}
			else {
389
				webRequest.getResponse().sendError(statusCode.value(), reason);
390
			}
391
		}
392 393 394 395 396

		if (returnValue != null && AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) != null) {
			return handleResponseBody(returnValue, webRequest);
		}

397 398 399 400 401 402 403
		if (returnValue instanceof ModelAndView) {
			return (ModelAndView) returnValue;
		}
		else if (returnValue instanceof Model) {
			return new ModelAndView().addAllObjects(((Model) returnValue).asMap());
		}
		else if (returnValue instanceof Map) {
404
			return new ModelAndView().addAllObjects((Map<String, Object>) returnValue);
405 406 407 408 409 410 411 412
		}
		else if (returnValue instanceof View) {
			return new ModelAndView((View) returnValue);
		}
		else if (returnValue instanceof String) {
			return new ModelAndView((String) returnValue);
		}
		else if (returnValue == null) {
413
			return new ModelAndView();
414 415 416 417 418 419
		}
		else {
			throw new IllegalArgumentException("Invalid handler method return value: " + returnValue);
		}
	}

P
Phillip Webb 已提交
420
	@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
421 422 423 424 425 426 427 428
	private ModelAndView handleResponseBody(Object returnValue, ServletWebRequest webRequest)
			throws ServletException, IOException {

		HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());
		List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
		if (acceptedMediaTypes.isEmpty()) {
			acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
		}
429
		MediaType.sortByQualityValue(acceptedMediaTypes);
430 431
		HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());
		Class<?> returnValueType = returnValue.getClass();
J
Juergen Hoeller 已提交
432
		if (this.messageConverters != null) {
433
			for (MediaType acceptedMediaType : acceptedMediaTypes) {
J
Juergen Hoeller 已提交
434
				for (HttpMessageConverter messageConverter : this.messageConverters) {
435 436 437 438 439 440 441 442 443 444 445 446 447 448
					if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
						messageConverter.write(returnValue, acceptedMediaType, outputMessage);
						return new ModelAndView();
					}
				}
			}
		}
		if (logger.isWarnEnabled()) {
			logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " +
					acceptedMediaTypes);
		}
		return null;
	}

449
}