SpringBoot之异常捕获(N)

来源:互联网 发布:sql脚本编写教程 编辑:程序博客网 时间:2024/06/05 17:26

创建一个java类GlobalDefaultExceptionHandler

1.在class注解上@ControllerAdvice
2.在方法上注解上@ExceptionHandler(value= Exception.class),具体代码如下

package cn.wuyang.springboot.config;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;@ControllerAdvicepublic class GlobalDefaultExceptionHandler {    /**     * 拦截所有Exception     */    @ExceptionHandler(Exception.class)    public String DefaultException(Exception e) {        //测试直接打印控制台        System.out.println("程序出错:"+e.getMessage());        return e.getMessage();    }}

测试一下定义一个方法

@RequestMapping("/test")    public int test() {        return 100/0;    }

访问出现结果

这里写图片描述

原创粉丝点击