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;
}
}
//局部异常处理(写在当前处理器内)方法上使用@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;
}
}
相关文章推荐
- 如何优雅地处理前端异常?
- C#异常处理详解
- 轻松学习C#的异常处理
- PHP异常处理Exception类
- JS异常处理的一个想法(sofish)
- PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法
- PHP如何抛出异常处理错误
- PHP中的错误处理、异常处理机制分析
- js中的异常处理try...catch使用介绍
- php5编程中的异常处理详细方法介绍
- php异常处理使用示例
- Asp.net Mvc 身份验证、异常处理、权限验证(拦截器)实现代码
- javascript 异常处理使用总结
- java多线程中的异常处理机制简析
- 深入理解Java编程中异常处理的优劣
- 分享一个php 的异常处理程序
- 简单了解Java编程中对异常处理的运用
- 深入剖析Java中的各种异常处理方式
- JS中的异常处理方法分享
- 一些.NET对多线程异常处理技巧分享