当前位置: 首页 > news >正文

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

在线工具站
  • 推荐一个程序员在线工具站:程序员常用工具(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 errorif (true) { // Replace with actual conditionthrow 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 {@Autowiredprivate MockMvc mockMvc;@Testpublic 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 和全局异常处理器进行进一步的扩展和优化。比如,添加更多的异常类型处理、记录日志、集成监控系统等。总之,良好的异常处理机制是构建高质量软件系统的重要一环。

http://www.lryc.cn/news/370909.html

相关文章:

  • Java 异常处理 -- Java 语言的异常、异常链与断言
  • Spring Cloud Nacos 详解:服务注册与发现及配置管理平台
  • java多线程临界区介绍
  • 基于JSP的超市管理系统
  • 一文讲清:生产报工系统的功能、报价以及如何选择
  • blender bpy将顶点颜色转换为UV纹理vertex color to texture
  • Flink Sql:四种Join方式详解(基于flink1.15官方文档)
  • (delphi11最新学习资料) Object Pascal 学习笔记---第14章泛型第3节(泛型约束)
  • C语言详解(预编译)
  • 解决el-table表格拖拽后,只改变了数据,表头没变的问题
  • 简单塔防小游戏
  • 高考之后第一张大流量卡应该怎么选?
  • 如何从微软官方下载Edge浏览器的完整离线安装包
  • git 常用的命令
  • 【StableDiffusion】Embedding 底层原理,Prompt Embedding,嵌入向量
  • 计算机网络(2) 网络层:IP服务模型
  • 新人学习笔记之(初识C语言)
  • Unity EasyRoads3D插件使用
  • Redis 地理散列GeoHash
  • vim 显示行号
  • C++:调整数组顺序使奇数位于偶数前面【面试】
  • WPF/C#:程序关闭的三种模式
  • 登录/注册- 滑动拼图验证码(IOS/Swift)
  • MyBatis进行模糊查询时SQL语句拼接引起的异常问题
  • 网站调用Edge浏览器API:https://api-edge.cognitive.microsofttranslator.com/translate
  • css实现优惠券样式
  • 函数递归(C语言)(详细过程!)
  • uniapp 接口请求封装
  • C++中的观察者模式
  • conda虚拟环境,安装pytorch cuda cudnn版本一致,最简单方式