在Java中使用Spring Boot设置全局的BusinessException

在线工具站
  • 推荐一个程序员在线工具站:程序员常用工具http://cxytools.com),有时间戳、JSON格式化、文本对比、HASH生成、UUID生成等常用工具,效率加倍嘎嘎好用。
程序员资料站
小报童专栏精选Top100
  • 推荐一个小报童专栏导航站:小报童精选Top100http://xbt100.top),收录了生财有术项目精选、AI海外赚钱、纯银的产品分析等专栏,陆续会收录更多的专栏,欢迎体验~

在企业级应用开发中,异常处理是一个重要的部分。通过统一处理异常,我们可以提高代码的可读性、减少重复代码、提高系统的健壮性。

什么是BusinessException?

BusinessException 是一种自定义的运行时异常,用于处理业务逻辑中的错误。例如,当用户试图执行一个未授权的操作时,抛出一个BusinessException,可以携带错误信息或错误码。这种异常可以帮助开发者更清晰地分离业务逻辑错误和系统错误。

创建BusinessException类

首先,我们需要创建一个自定义的异常类 BusinessException。这个类应该继承自 RuntimeException,并且可以包含一个错误码和一个错误信息。

java 复制代码
public class BusinessException extends RuntimeException {
    private int errorCode;

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public int getErrorCode() {
        return errorCode;
    }
}

创建全局异常处理器

为了统一处理 BusinessException,我们需要创建一个全局异常处理器。Spring Boot 提供了 @ControllerAdvice 注解来实现全局异常处理。

java 复制代码
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(BusinessException ex, WebRequest request) {
        ErrorResponse errorResponse = new ErrorResponse(ex.getErrorCode(), ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex, WebRequest request) {
        ErrorResponse errorResponse = new ErrorResponse(500, "Internal Server Error");
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

创建ErrorResponse类

为了统一返回错误信息,我们可以创建一个 ErrorResponse 类。

java 复制代码
public class ErrorResponse {
    private int errorCode;
    private String errorMessage;

    public ErrorResponse(int errorCode, String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    // Getters and Setters
}

在业务逻辑中使用BusinessException

现在,我们可以在业务逻辑中使用 BusinessException 来处理业务错误。下面是一个示例控制器,演示如何在业务逻辑中抛出 BusinessException

java 复制代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class SampleController {

    @GetMapping("/test")
    public String testEndpoint() {
        // Simulate a business logic error
        if (true) { // Replace with actual condition
            throw new BusinessException(1001, "Business logic error occurred");
        }
        return "Success";
    }
}

测试全局异常处理

为了测试我们的全局异常处理,我们可以编写一个简单的单元测试。

java 复制代码
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(SampleController.class)
public class SampleControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testBusinessException() throws Exception {
        mockMvc.perform(get("/api/test"))
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.errorCode").value(1001))
                .andExpect(jsonPath("$.errorMessage").value("Business logic error occurred"));
    }
}

结论

通过本文的介绍,我们了解了如何在Spring Boot中设置全局的 BusinessException。这种统一的异常处理机制不仅可以提高代码的可读性和维护性,还能为用户提供更友好的错误信息。

在实际项目中,你可能需要根据具体需求对 BusinessException 和全局异常处理器进行进一步的扩展和优化。比如,添加更多的异常类型处理、记录日志、集成监控系统等。总之,良好的异常处理机制是构建高质量软件系统的重要一环。

相关推荐
救救孩子把14 分钟前
深入理解 Java 对象的内存布局
java
落落落sss17 分钟前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
万物皆字节22 分钟前
maven指定模块快速打包idea插件Quick Maven Package
java
夜雨翦春韭29 分钟前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
简单.is.good35 分钟前
【测试】接口测试与接口自动化
开发语言·python
我行我素,向往自由36 分钟前
速成java记录(上)
java·速成
一直学习永不止步42 分钟前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
邵泽明42 分钟前
面试知识储备-多线程
java·面试·职场和发展
Yvemil71 小时前
MQ 架构设计原理与消息中间件详解(二)
开发语言·后端·ruby
程序员是干活的1 小时前
私家车开车回家过节会发生什么事情
java·开发语言·软件构建·1024程序员节