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(),"请检查参数");
    }
}
相关推荐
渣哥19 小时前
ConcurrentHashMap 的 get 要不要加锁?一次“多此一举”的心路历程
java
愿你天黑有灯下雨有伞19 小时前
一种基于注解与AOP的Spring Boot接口限流防刷方案
java·spring boot·后端
MuMuMu#19 小时前
JAVA NIO学习笔记基础强化学习总结
java·学习·nio
拾忆,想起19 小时前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化
我登哥MVP19 小时前
Java File 类学习笔记
java·笔记·学习
爬山算法19 小时前
Redis(47)如何配置Redis哨兵?
数据库·redis·bootstrap
掘根19 小时前
【CMake】缓存变量
java·后端·spring
西京刀客19 小时前
macos安装openjdk17
java·macos·java17
知识浅谈20 小时前
Redis哨兵模式在Spring Boot项目中的使用与实践
spring boot·redis·bootstrap
Java中文社群20 小时前
面试官:如何实现动态线程池的任务编排?
java·后端·面试