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

发布于:2024-06-16 ⋅ 阅读:(24) ⋅ 点赞:(0)
在线工具站
  • 推荐一个程序员在线工具站:程序员常用工具(http://cxytools.com),有时间戳、JSON格式化、文本对比、HASH生成、UUID生成等常用工具,效率加倍嘎嘎好用。
程序员资料站
  • 推荐一个程序员编程资料站:程序员的成长之路(http://cxyroad.com),收录了一些列的技术教程、各大面试专题,还有常用开发工具的教程。
小报童专栏精选Top100
  • 推荐一个小报童专栏导航站:小报童精选Top100(http://xbt100.top),收录了生财有术项目精选、AI海外赚钱、纯银的产品分析等专栏,陆续会收录更多的专栏,欢迎体验~

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

什么是BusinessException?

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

创建BusinessException类

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

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 注解来实现全局异常处理。

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 类。

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

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";
    }
}

测试全局异常处理

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

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