SpringMVC异常处理

来源:互联网 发布:乐视淘宝旗舰店负责人 编辑:程序博客网 时间:2024/05/19 01:07

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注解

@ControllerAdvice
public class HandlerExceptionHandler {

 @ExceptionHandler({ArithmeticException.class})
 public ModelAndView handlerArithmeticException(Exception e){
  System.out.println("===>出异常了:"+e);
  ModelAndView mav=new ModelAndView("error");
  mav.addObject("exception", e);
  return mav;
 }
}


0 0
原创粉丝点击