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

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

1.注解

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

2.配置类

@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 会自动捕获到该异常,并按照配置类中声明的返回体响应给前端

if (true){
    throw new NewRuntimException(500,"测试异常");
}

4.自定义异常类

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

4.1配置类实例

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使用

public boolean indexExist(String index) {
    if (true){
        throw new NewRuntimException(ResultCode.E_400.getCode(),"请检查参数");
    }
}
目录
相关文章
|
6天前
|
JSON 前端开发 Java
解决Spring MVC中No converter found for return value of type异常
在Spring MVC开发中遇到`No converter found for return value of type`异常,通常是因缺少消息转换器、返回值类型不支持或转换器优先级配置错误。解决方案包括:1) 添加对应的消息转换器,如`MappingJackson2HttpMessageConverter`;2) 自定义消息转换器并实现`HttpMessageConverter`接口,设置优先级;3) 修改返回值类型为如`ResponseEntity`的合适类型。通过这些方法可确保返回值正确转换为响应内容。
44 1
|
6天前
|
Java 数据库 Spring
Spring Boot的异常统一处理实战(包括@ExceptionHandler注解和@ControllerAdvice注解 附源码 超详细)
Spring Boot的异常统一处理实战(包括@ExceptionHandler注解和@ControllerAdvice注解 附源码 超详细)
98 0
|
6天前
|
消息中间件 监控 Java
Spring Boot中的RabbitMQ死信队列魔法:从异常到延迟,一网打尽【RabbitMQ实战 一】
Spring Boot中的RabbitMQ死信队列魔法:从异常到延迟,一网打尽【RabbitMQ实战 一】
99 0
|
6天前
|
Java
springboot全局自定义异常
springboot全局自定义异常
|
6天前
|
安全 前端开发 Java
Spring Security 自定义异常失效?从源码分析到解决方案
Spring Security 自定义异常失效?从源码分析到解决方案
|
6天前
|
Java 关系型数据库 MySQL
整合SpringBoot与MyBatis时报错时区异常
整合SpringBoot与MyBatis时报错时区异常
15 0
|
6天前
|
JSON 前端开发 Java
统一异常处理:让Spring Boot项目异常更优雅
统一异常处理:让Spring Boot项目异常更优雅
33 1
|
6天前
|
Java
SpringBoot全局异常代码复制粘贴能用
SpringBoot全局异常代码复制粘贴能用
10 0
|
6天前
|
Java
SpringBoot配置全局异常
SpringBoot配置全局异常
11 0
|
6天前
|
Java
SpringBoot全局异常@RestControllerAdvice全局异常
SpringBoot全局异常@RestControllerAdvice全局异常
12 0