在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 和全局异常处理器进行进一步的扩展和优化。比如,添加更多的异常类型处理、记录日志、集成监控系统等。总之,良好的异常处理机制是构建高质量软件系统的重要一环。

相关推荐
AD钙奶-lalala11 分钟前
Mac OS上搭建 http server
java
TomCode先生1 小时前
c#动态树形表达式详解
开发语言·c#
高-老师2 小时前
基于R语言的物种气候生态位动态量化与分布特征模拟
开发语言·r语言·物种气候
大翻哥哥2 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
weixin_437830943 小时前
使用冰狐智能辅助实现图形列表自动点击:OCR与HID技术详解
开发语言·javascript·ocr
鹿鹿学长3 小时前
2025年全国大学生数学建模竞赛(C题) 建模解析|婴儿染色体数学建模|小鹿学长带队指引全代码文章与思路
c语言·开发语言·数学建模
zhousenshan3 小时前
Python爬虫常用框架
开发语言·爬虫·python
皮皮林5514 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904274 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_4 小时前
异步编程CompletionService
java