问题:使用@ExceptionHandle注解须要在每个controller代码里面都添加异常处理,会咋成代码冗余web
解决方法:新建一个全局异常处理类,添加@ControllerAdvice注解便可spring
package com.bjsxt.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; /** * Created by Administrator on 2019/2/14. * 全局异常处理类 */ @ControllerAdvice public class GlobalException { /** * 处理ArithmeticException异常,该@ExceptionHandler注释的value属性能够是一个数组, * 而后再根据注入的exception判断对不一样异常分别进行不一样的处理,也能够写多个controller, * 对多个不一样异常进行处理,这里采用第二种 * @param e 会将产生异常对象注入到方法中 * @return 该方法须要返回一个 ModelAndView:目的是可让咱们封装异常信息以及视图的指定 */ @ExceptionHandler(value = {ArithmeticException.class}) public ModelAndView arithmeticExceptionHandler(Exception e){ ModelAndView mv=new ModelAndView("error_arithmetic"); mv.addObject("msg",e.toString()); return mv; } /** * 处理NullPointerException异常 * @param e 会将产生异常对象注入到方法中 * @return 该方法须要返回一个 ModelAndView:目的是可让咱们封装异常信息以及视图的指定 */ @ExceptionHandler(value = {NullPointerException.class}) public ModelAndView nullPointerExceptionHandler(Exception e){ ModelAndView mv=new ModelAndView("error_nullPointer"); mv.addObject("msg",e.toString()); return mv; } }