SpringMvc异常处理

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

DispatcheServlet默认装配了的HandlerExceptionResolver:

   没有使用<mvc:annotation-driven/>配置:

使用了<mvc:annotation-driven/>配置:

ExceptionHandlerExceptionResolver

         主要处理Handler中用@ExceptionHandler注解定义的方法。

         @ExceptionHandler注解定义的方法优先级问题:例如发生的是NullPointerException,但是声明的异常有RuntimeException和Exception,此时会根据异常的最近继承关系找到继承深度最浅的那个@ExceptionHandler注解定义的方法,及标记了RuntimeException的方法。

package com.seven.exceptionHandler;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by hu on 2016/4/4.
 */
@ControllerAdvice
public class SpringMvcTestExceptionHandler {
    @ExceptionHandler({ArithmeticException.class})
    public ModelAndView handleArithmeticException(Exception e){
        System.out.println("---->出现异常了:"+e);
        //转到逻辑名为error的视图
        ModelAndView modelAndView=new ModelAndView("error");
        modelAndView.addObject("exception",e);
        return modelAndView;
    }
}

 ResponseStatusExceptionResolver

        在异常及异常的父类中找到@ResponseStatus注解,然后使用这个注解的属性进行处理。

package com.seven.exceptionHandler;

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

/**
 * Created by hu on 2016/4/4.
 */
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extends RuntimeException{
    /*
    * 当程序发生UserNameNotMatchPasswordException这个异常的时,
    * 由于触发的这个异常带有@ResponseStatus注解,因此会被ResponseStatusExceptionResolver解析,
    * 那么响应的状态是FORBIDDEN,代码是401,无权限。原因是 "用户名和密码不匹配!"
    * 一并返回给客户端
    * */
}

DefaultHandlerExceptionResolver

对一些特殊的异常进行处理,比如以下的异常:

SimpleMappingExceptionResolver

    如果希望所有异常进行同意的处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常

       <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
              <!--定义异常处理页面来获取异常信息的变量名,默认为exception-->
              <property name="exceptionAttribute" value="ex"></property>
              <property name="exceptionMappings">
                     <props>
                            <!--如果出现下面这个异常,就映射到error这个页面上-->
                            <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
                     </props>
              </property>
       </bean>

  

 

原文地址:https://www.cnblogs.com/hujingwei/p/5351495.html