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(),"请检查参数");
    }
}
相关推荐
摇滚侠10 分钟前
MyBatis 入门到项目实战 特殊 SQL 的执行 34-37
java·sql·mybatis
huangdong_10 分钟前
京东商品图片视频批量下载与m3u8视频合并技术完整实现方案
大数据·前端·数据库
倒流时光三十年19 分钟前
PostgreSQL CASE 条件表达式详解
数据库·postgresql
phltxy40 分钟前
Spring AI 可观测性与 Zipkin 实战
java·人工智能·spring
字节跳动数据平台41 分钟前
营销视频进入工业化时代,火山引擎多模态数据湖如何助力多米实现内容生产提效 100+ 倍
数据库
兰令水1 小时前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
.道阻且长.1 小时前
C++ string 操作指南:接口解析
java·c语言·开发语言·c++
蚰蜒螟1 小时前
Java 对象的内存密语:从字段偏移量计算到 Unsafe 访问的完整链路
java·开发语言
IT 行者1 小时前
GitHub Spec Kit 实战(六):/speckit.implement 怎么用、怎么审、怎么发现 spec 阶段的遗漏——五部曲收官
java·驱动开发·github·ai编程·claude
健康平安的活着1 小时前
mysql中数据库脚本太大,通过脚本命令修改db名称
数据库·mysql