您的位置:首页 > 编程语言 > Java开发

SpringMVC异常处理

2016-06-01 22:10 453 查看
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;

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc 异常处理