news 2026/4/15 6:23:55

简单业务异常类

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
简单业务异常类

一、最简版本(适合新手)

import lombok.Getter; /** * 业务异常 - 最简单版本 */ @Getter public class BusinessException extends RuntimeException { private final Integer code; // 错误码 // 构造方法1:指定错误码和消息 public BusinessException(Integer code, String message) { super(message); this.code = code; } // 构造方法2:只传消息,默认500错误码 public BusinessException(String message) { this(500, message); } }

二、稍微丰富版本(推荐)

import lombok.Getter; /** * 业务异常 - 常用版本 */ @Getter public class BusinessException extends RuntimeException { private final Integer code; // 常用状态码定义 public static final Integer BAD_REQUEST = 400; // 请求参数错误 public static final Integer UNAUTHORIZED = 401; // 未授权 public static final Integer FORBIDDEN = 403; // 禁止访问 public static final Integer NOT_FOUND = 404; // 资源不存在 // 常用构造方法 public BusinessException(Integer code, String message) { super(message); this.code = code; } public BusinessException(String message) { this(500, message); } // 快速创建方法(静态工厂方法) public static BusinessException badRequest(String message) { return new BusinessException(BAD_REQUEST, message); } public static BusinessException notFound(String resourceName) { return new BusinessException(NOT_FOUND, resourceName + "不存在"); } public static BusinessException forbidden() { return new BusinessException(FORBIDDEN, "无权限访问"); } }

三、配合枚举使用

// 1. 先定义错误枚举 @Getter public enum ErrorCode { SUCCESS(200, "成功"), PARAM_ERROR(400, "参数错误"), UNAUTHORIZED(401, "未登录"), FORBIDDEN(403, "无权限"), NOT_FOUND(404, "资源不存在"), USER_NOT_FOUND(40401, "用户不存在"), SYSTEM_ERROR(500, "系统错误"); private final Integer code; private final String message; ErrorCode(Integer code, String message) { this.code = code; this.message = message; } } // 2. 修改异常类 @Getter public class BusinessException extends RuntimeException { private final Integer code; // 使用枚举构造 public BusinessException(ErrorCode errorCode) { super(errorCode.getMessage()); this.code = errorCode.getCode(); } // 自定义消息 public BusinessException(ErrorCode errorCode, String customMessage) { super(customMessage); this.code = errorCode.getCode(); } }

四、实际使用例子

@Service public class UserService { public User getUserById(Long id) { User user = userRepository.findById(id); // 情况1:直接抛异常 if (user == null) { throw new BusinessException(404, "用户不存在"); } // 情况2:使用快速方法 if (user.getStatus() == 0) { throw BusinessException.forbidden(); } // 情况3:使用枚举 if (user.getBalance() < 0) { throw new BusinessException(ErrorCode.PARAM_ERROR, "余额不能为负"); } return user; } public void transfer(Long fromId, Long toId, BigDecimal amount) { // 使用连串校验 User fromUser = userRepository.findById(fromId) .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND)); if (fromUser.getBalance().compareTo(amount) < 0) { throw new BusinessException(400, "余额不足"); } // 业务逻辑... } }

五、全局异常处理

@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(BusinessException.class) public Result<?> handleBusinessException(BusinessException e) { // 统一返回格式 return Result.error(e.getCode(), e.getMessage()); } @ExceptionHandler(Exception.class) public Result<?> handleOtherException(Exception e) { // 其他异常 log.error("系统异常", e); return Result.error(500, "系统异常"); } } // 统一返回结果 @Data class Result<T> { private Integer code; private String message; private T data; public static <T> Result<T> success(T data) { Result<T> result = new Result<>(); result.code = 200; result.message = "成功"; result.data = data; return result; } public static <T> Result<T> error(Integer code, String message) { Result<T> result = new Result<>(); result.code = code; result.message = message; return result; } }

六、总结要点

最简写法(记住这个就行):

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

使用三部曲:

  1. 定义异常类(上面代码)

  2. 在需要的地方抛出

    if (条件不满足) { throw new BusinessException(400, "错误信息"); }
  3. 全局处理(返回统一格式)

记住几个常用错误码:

  • 400:参数错误

  • 401:未登录

  • 403:无权限

  • 404:不存在

  • 500:系统错误

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/9 22:32:10

解析企业微信身份验证机制 UserID OpenID ExternalUserID 及其转换方法

一、引言 (Introduction) 1.1 背景&#xff1a; 企业微信在设计上严格区分了内部用户、外部客户和非企业微信用户&#xff0c;形成了多套身份标识体系。 1.2 目的&#xff1a; 深入解析企业微信中 $UserID$、$OpenID$ 和 $ExternalUserID$ 三种核心身份标识的含义、作用范围&a…

作者头像 李华
网站建设 2026/4/12 22:44:31

React 官方严令禁止:Hook 不能写在 if/else,真相竟然是…

React 官方严令禁止&#xff1a;Hook 不能写在 if/else&#xff0c;真相竟然是… 在 React 中&#xff0c;Hook 不能放在 if/else、循环或者 switch 语句中&#xff0c;否则会导致 React 的 Hook 规则被破坏&#xff0c;最终引发错误。 一、错误示例 function MyComponent() {c…

作者头像 李华
网站建设 2026/4/13 4:50:29

计算机毕业设计springboot药店管理系统 基于SpringBoot的药品零售信息管理平台 SpringBoot驱动的智慧药房综合运营系统

计算机毕业设计springboot药店管理系统04t639km &#xff08;配套有源码 程序 mysql数据库 论文&#xff09; 本套源码可以在文本联xi,先看具体系统功能演示视频领取&#xff0c;可分享源码参考。传统药店每天需要处理大量药品的流转、库存、销售与顾客服务&#xff0c;人工台账…

作者头像 李华
网站建设 2026/4/3 10:18:58

17、Linux 网络与内核管理及任务自动化全解析

Linux 网络与内核管理及任务自动化全解析 1. 无线设备与黑客技术 无线设备是未来连接和黑客攻击的重要领域。Linux 系统开发了专门的命令用于扫描和连接 Wi-Fi 接入点(AP),这是对这些系统进行黑客攻击的第一步。 无线黑客工具套件 aircrack - ng 套件 :包含 airmon -…

作者头像 李华
网站建设 2026/4/6 14:10:44

编程考级避坑指南:三大误区需警惕

编程考级避坑指南:三大误区需警惕 很多家长关心孩子学习编程后是否需要参加考级,以及如何选择适合的考试。编程考级并非学习的最终目标,但如果选择得当,可以有效帮助孩子梳理知识体系,提升综合能力。 一、考级的真正意义:避开三个常见误区 考级的核心在于“以考促学”…

作者头像 李华