Spring-自定义异常及全局异常处理@RestControllerAdvice

前言

开发中,经常需要对业务异常进行处理;而往往业务中会出现很多种情况需要进行业务处理,例如查询人员数据为空、人员角色不符、人员收货地址不存在等等,都需要try catch进行不同的处理。这样的try catch会造成大量的重复代码,此时就需要全局异常捕获@RestControllerAdvice,通过它来构建一个全局捕获根据不同的异常类型来进行统一的处理。

1、构建自定义业务异常-BusinessException

public class BusinessException extends RuntimeException {

    private Integer code;

    private String message;

    public BusinessException(Integer code, String message) {
        super();
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

2、创建全局统一异常处理

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
	// 统一处理业务异常-BusinessException
    @ExceptionHandler(value = BusinessException.class)
    public NormalResponse businessException(HttpServletRequest request,BusinessException e){
        log.error("{}请求异常{}",request.getRequestURL(),e.getMessage());
        return NormalResponse.fail(e.getMessage());
    }
  }

3、在业务中使用

    public void testGlobalException() {
        // 业务处理...
        Student student = studentMapper.selectById(10086);
        if (Objects.isNull(student)) {
            throw new BusinessException(20001, "查询人员不存在");
        }
        // 正常逻辑处理...
    }

假设我们在业务处理中,需要查询id=10086的学生,然后对这个学生的信息进行处理(更新,添加字段等),当查询人员不存在时,需要提醒接口调用方出现了业务问题-查询人员不存在。

4、演示结果

控制台日志:
2024-09-10 15:48:15.893 ERROR 51752 --- [nio-6024-exec-3] c.s.d.exception.GlobalExceptionHandler   : http://localhost:6024/test/global-exception请求异常查询人员不存在
15:48:15.893 [http-nio-6024-exec-3] ERROR c.s.d.e.GlobalExceptionHandler - http://localhost:6024/test/global-exception请求异常查询人员不存在

postman接口返参:
{
    "code": -1,
    "message": null,
    "data": "查询人员不存在"
}
相关推荐
m0_748247551 小时前
springboot中配置logback-spring.xml
spring boot·spring·logback
计算机-秋大田2 小时前
基于Spring Boot的农产品智慧物流系统设计与实现(LW+源码+讲解)
java·开发语言·spring boot·后端·spring·课程设计
计算机毕设指导62 小时前
基于SpringBoot的城乡商城协作系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
caihuayuan43 小时前
PHP建立MySQL持久化连接(长连接)及mysql与mysqli扩展的区别
java·大数据·sql·spring
_风中无我。4 小时前
Spring的过滤器获取请求体中JSON参数,同时解决Controller获取不到请求体参数的问题。
java·spring·json
Swift社区5 小时前
【微服务优化】ELK日志聚合与查询性能提升实战指南
spring·elk·微服务·云原生·架构
White graces15 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
是姜姜啊!16 小时前
redis的应用,缓存,分布式锁
java·redis·spring
奋斗的袍子00718 小时前
Spring AI + Ollama 实现调用DeepSeek-R1模型API
人工智能·spring boot·深度学习·spring·springai·deepseek
LUCIAZZZ18 小时前
EasyExcel快速入门
java·数据库·后端·mysql·spring·spring cloud·easyexcel