SpringMVC异常处理分局部异常处理和全局异常处理,首先在局部异常处理中找匹配精准度最高的,若找不到就去找全局异常处理
//局部异常处理(写在当前处理器内)方法上使用@ExceptionHandler注解
@Controller
public class SpringMVCTest {
@ExceptionHandler({RuntimeException.class})
public ModelAndView handlerRuntimeException(Exception e){
System.out.println("出异常了:"+e);
ModelAndView mav=new ModelAndView("error");
mav.addObject("exception", e);
return mav;
}
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handlerArithmeticException(Exception e){ //精准度更高,优先匹配这个
System.out.println("-->出异常了:"+e);
ModelAndView mav=new ModelAndView("error");
mav.addObject("exception", e);
return mav;
}
@RequestMapping("/testExceptionHandlerExceptionResolver")
public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
System.out.println("result:" +(10/i)); //i=0时发生ArithmeticException
return "success";
}
}
//全局异常处理(专门写一个处理器类)类上使用@ControllerAdvice注解,方法上使用@ExceptionHandler注解
public class HandlerExceptionHandler {
public ModelAndView handlerArithmeticException(Exception e){
System.out.println("===>出异常了:"+e);
ModelAndView mav=new ModelAndView("error");
mav.addObject("exception", e);
return mav;
}
}