SpringMVC之异常处理

时间:2019-11-20
本文章向大家介绍SpringMVC之异常处理,主要包括SpringMVC之异常处理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1 概述

  • SpringMVC通过HandlerExceptionResolver处理程序的异常,包括Handler映射、数据绑定以及目标方法执行时发生的异常。
  • SpringMVC提供的HandlerExceptionResolver的实现类如下:

2 ExceptionHandlerExceptionResolver

  • 主要处理Handler中用@ExceptionHandler注解定义的方法。
  • @ExceptionHandler注解定义的方法优先级问题:如果发生的异常时NullPointerException,但是声明的异常由RuntimeException和Exception,此时会根据异常的最近继承关系找到继承深度最浅的哪个@ExceptionHandler注解方法,即标记了RuntimeException的方法。
  • ExceptionHandlerExceptionResolver内部如果找不到@ExceptionHandler注解的话,就会找@ControllerAdvice中的@ExceptionHandler注解方法。

3 ResponseStatusExceptionResolver

  • 在异常及异常父类中找到@ResponseStatus注解,然后使用这个注解的属性进行处理。
  • 定义一个@ResponseStatus注解修饰的异常类:
package com.sunxiaping.springmvc.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends RuntimeException {
}
  • 如果在处理器方案分中抛出了上述异常:假如ExceptionHandlerExceptionResolver不解析该异常,由于触发的异常UnauthorizedException带有@ResponseStatus注解。因此会被ResponseStatusExceptionResolver解析到,最后响应HttpStatus.UNAUTHORIZED代码到客户端。

4 DefaultHandlerExceptionResolver

  • 对一些特殊的异常处理,比如NoSuchRequestHandingMethodException、HttpRequestMethodNotSupportedException、HttpMediaTypeNotSupportedException等。

5 SimpleMappingExceptionHandler

  • 如果希望对所有的异常进行处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常。
<bean id="simpleMappingExceptionResolver"
      class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="java.lang.ArithmeticException">error</prop>
        </props>
    </property>
</bean>

原文地址:https://www.cnblogs.com/xuweiweiwoaini/p/11900584.html