Spring 异常处理的三种方式 整理

  1. 异常处理方式一. @ExceptionHandler
  2. 异常处理方式二. 实现HandlerExceptionResolver接口
  3. 异常处理方式三. @ControllerAdvice+@ExceptionHandler
  4. 三种方式比较说明(强烈推荐各位看一下,我觉得自己总结的比较多,嘿嘿,不对之处请指出,点我快速前往!)

 

问题描述: 假如对异常不进行处理?

假如SpringMvc我们不对异常进行任何处理, 界面上显示的是这样的.

image

 

异常处理的方式有三种:

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) </

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值