springmvc学习笔记(29)——@ExceptionHandle 注解

HandleException的优先级
当一个controller中有多个HandleException注解出现时,那么异常被哪个方法捕捉呢?这就存在一个优先级的问题   

@ExceptionHandler({ArithmeticException.class})
    public String testArithmeticException(Exception e){
        System.out.println("ArithmeticException:"+e);
        return "error";
    }

    @ExceptionHandler({RuntimeException.class})
    public String testRuntimeException(Exception e){
        System.out.println("RuntimeException"+e);
        return "error";
    }

    @RequestMapping("testExceptionHandle")
    public String testExceptionHandle(@RequestParam("i")Integer i){
        System.out.println(10/i);
        return "hello";
    }


如以上代码所示,目标方法是testExceptionHandle,另外两个方法被ExceptionHandler注解修饰。

因此我们可以确定,ExceptionHandler的优先级是:在异常的体系结构中,哪个异常与目标方法抛出的异常血缘关系越紧密,就会被哪个捕捉到。

捕捉全局的异常
ExceptionHandler只能捕捉同一个controller中的异常,其实我们也有办法捕捉整个程序中所有的异常

新建一个类,加上@ControllerAdvice注解
 

package com.zj.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

//处理异常
@ControllerAdvice
public class HandleForException {

    @ExceptionHandler({ArithmeticException.class})
    public String testArithmeticException(Exception e){
        System.out.println("ArithmeticException:"+e);
        return "error";
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36826506/article/details/84996800