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(),"请检查参数");
    }
}
相关推荐
淘源码d18 小时前
什么是医院随访系统?成熟在用的智慧随访系统源码
java·spring boot·后端·开源·源码·随访系统·随访系统框架
qq_54702617919 小时前
Canal实时同步MySQL数据到Elasticsearch
数据库·mysql·elasticsearch
程序猿阿越19 小时前
Kafka源码(七)事务消息
java·后端·源码阅读
m0_7482480219 小时前
C++20 协程:在 AI 推理引擎中的深度应用
java·c++·人工智能·c++20
笑我归无处19 小时前
强引用、软引用、弱引用、虚引用详解
java·开发语言·jvm
02苏_19 小时前
秋招Java面
java·开发语言
Q_Q196328847519 小时前
python+django/flask基于机器学习的就业岗位推荐系统
spring boot·python·django·flask·node.js·php
爱吃甜品的糯米团子19 小时前
详解 JavaScript 内置对象与包装类型:方法、案例与实战
java·开发语言·javascript
ArabySide19 小时前
【Spring Boot】REST与RESTful详解,基于Spring Boot的RESTful API实现
spring boot·后端·restful
java1234_小锋20 小时前
REDIS集群会有写操作丢失吗?为什么
数据库·redis·缓存