Springboot简单利用@RestControllerAdvice优雅的捕获异常

1.注解

@ExceptionHandler:用于指定异常处理方法。当与@RestControllerAdvice配合使用时,用于全局处理控制器里的异常。

2.配置类

java 复制代码
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("系统异常", e);
        return ResultGenerator.genResult(ResultCode.E_500.getCode(), e.getMessage(), null);
    }
    @ExceptionHandler(NewRuntimException.class)
    public Result handleException(NewRuntimException e) {
        log.error("请求异常被程序拦截", e);
        return e.getErrorCode() == 0 ? ResultGenerator.genResult(ResultCode.E_500.getCode(), e.getMessage(), null) : ResultGenerator.genResult(e.getErrorCode(), e.getMessage(), null);
    }
}

3.使用

当项目在运行时抛出NewRuntimException或者我们手动抛出NewRuntimException后,GlobalExceptionHandler 会自动捕获到该异常,并按照配置类中声明的返回体响应给前端

java 复制代码
if (true){
    throw new NewRuntimException(500,"测试异常");
}

4.自定义异常类

新建一个配置类,并继承RunRuntimeException即可,可以添加有参构造方法,用来声明异常code

4.1配置类实例

java 复制代码
public class NewRuntimException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    private int errorCode;
    public NewRuntimException(String msg) {
        super(msg);
    }
    public NewRuntimException(int errorCode, String msg) {
        super(msg);
        //自定义错误码
        this.setErrorCode(errorCode);
    }
    public int getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
}

4.2使用

java 复制代码
public boolean indexExist(String index) {
    if (true){
        throw new NewRuntimException(ResultCode.E_400.getCode(),"请检查参数");
    }
}
相关推荐
qhd吴飞几秒前
mybatis 差异更新法
java·前端·mybatis
YuTaoShao23 分钟前
【LeetCode 热题 100】51. N 皇后——回溯
java·算法·leetcode·职场和发展
angushine30 分钟前
logstash采集springboot微服务日志
spring boot·微服务·linq
-XWB-38 分钟前
【Oracle】套接字异常(SocketException)背后隐藏的Oracle问题:ORA-03137深度排查与解决之道
数据库·oracle
null不是我干的42 分钟前
基于黑马教程——微服务架构解析(一)
java·微服务·架构
睿思达DBA_WGX43 分钟前
由于主库切换归档路径导致的 Oracle DG 无法同步问题的解决过程
运维·数据库·oracle
Bonnie_12151 小时前
04-netty基础-Reactor三种模型
java·nio·jetty
懂得节能嘛.1 小时前
【SpringAI实战】ChatPDF实现RAG知识库
java·后端·spring
探索java1 小时前
Spring 解析 XML 配置文件的过程(从读取 XML 到生成 BeanDefinition)
xml·java·spring·xmlbeanfactory
武昌库里写JAVA1 小时前
「mysql」Mac osx彻底删除mysql
vue.js·spring boot·毕业设计·layui·课程设计