- 异常处理方式一. @ExceptionHandler
- 异常处理方式二. 实现HandlerExceptionResolver接口
- 异常处理方式三. @ControllerAdvice+@ExceptionHandler
- 三种方式比较说明(强烈推荐各位看一下,我觉得自己总结的比较多,嘿嘿,不对之处请指出,点我快速前往!)
问题描述: 假如对异常不进行处理?
假如SpringMvc我们不对异常进行任何处理, 界面上显示的是这样的.

异常处理的方式有三种:
1|0一. Controller层面上异常处理 @ExceptionHandler
说明:针对可能出问题的Controller,新增注解方法@ExceptionHandler.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 |
@Controller @RequestMapping ( "/testController" ) public class TestController {
@RequestMapping ( "/demo1" ) @ResponseBody public Object demo1(){
int i = 1 / 0 ; return new Date(); } @ExceptionHandler ({RuntimeException. class }) public ModelAndView fix(Exception ex){
System.out.println( "do This" ); return new ModelAndView( "error" , new ModelMap( "ex" ,ex.getMessage())); } } |
注意事项: 1. 一个Controller下多个@ExceptionHandler上的异常类型不能出现一样的,否则运行时抛异常.
Ambiguous @ExceptionHandler method mapped for;
2. @ExceptionHandler下方法返回值类型支持多种,常见的ModelAndView,@ResponseBody注解标注,ResponseEntity等类型都OK.
原理说明:
代码片段位于:org.springframework.web.servlet.DispatcherServlet#doDispatch
执行@RequestMapping方法抛出异常后,Spring框架 try-catch的方法捕获异常, 正常逻辑发不发生异常都会走processDispatchResult流程 ,区别在于异常的参数是否为null .
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 |
HandlerExecutionChain mappedHandler = null ; Exception dispatchException = null ; ModelAndView mv = null ; try {
mappedHandler=getHandler(request); //根据请求查找handlerMapping找到controller HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); //找到处理器适配器HandlerAdapter if (!mappedHandler.applyPreHandle(request,response)){ //拦截器preHandle return ; } mv=ha.handle(request,response); //调用处理器适配器执行@RequestMapping方法 mappedHandler.applyPostHandle(request,response,mv); //拦截器postHandle } catch (Exception ex){
dispatchException=ex; } processDispatchResult(request,response,mappedHandler,mv,dispatchException)
|