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

简单业务异常类

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

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:系统错误

http://www.cnnetsun.cn/news/23776.html

相关文章:

  • 5分钟掌握RichTextKit:SwiftUI富文本编辑器终极指南
  • 如何有效准备编程竞赛?五个阶段科学备考方法
  • BG3模组管理器终极指南:5分钟快速上手博德之门3模组管理
  • 6、黑客必备:Linux 网络技能与软件管理
  • Font Awesome 7全面解析:现代化图标解决方案的革新之路
  • MySQL业务数据量增长到单表成为瓶颈时,该如何做?
  • 13、Linux 系统日志处理与服务使用技巧
  • Paperzz 论文查重:从 “重复率焦虑” 到 “合规清晰”,学术新人如何用工具搞定论文的 “终稿安检”
  • Bananas屏幕共享:3分钟学会零门槛跨平台协作
  • 使用二进制文件方式部署kubernetes(1)
  • 如何在Mac上安装KeyCastr:5步搞定按键可视化工具
  • 小学生学C++编程 (位运算精讲)
  • 鸿蒙投屏工具HOScrcpy深度实战:突破传统镜像的进阶玩法
  • 基于MATLAB的胃癌检测实现方案
  • 图像分割新利器:预训练骨干网络快速构建高质量分割模型
  • 论文重复率 / AI 率双超?paperxie 的 “精准优化” 功能:如何在不碰专业内容的前提下过检测?
  • 36、Linux 系统安全防护全攻略
  • React Native语音识别终极指南:让你的应用听懂用户心声
  • 水银温度计淘汰不用慌!健康一体机:测温只是开始,多项目检测才是核心
  • 突然发布!GPT-5.2深夜来袭,3个版本碾压人类专家,打工人该怎么选?
  • 字符串特性解析:Python不可变性引发的错误
  • 【万字长文】大模型与智能体本质区别解析:系统级架构与模型升级的对比与应用指南!
  • 从零开始构建Agentic RAG:结合RAG与AI Agent的大模型新范式实战指南!
  • EasyPoi 数据脱敏
  • 收藏必备!GPT-5.2震撼发布:OpenAI反击战,职场程序员的AI新神器
  • 3步上手Sparta:让网络安全渗透测试变得像玩游戏一样简单
  • Android媒体画廊应用终极指南:轻量级隐私保护的完美选择
  • FT8371A,FT8371B,FT8371C 次边同步整流芯片典型应用资料分析
  • 智慧文旅信创落地新标杆:四川省文旅厅完成MySQL 5.7平滑替换,筑牢省级管理平台自主可控底座
  • 7、Unix/Linux 网络监控与日志管理全解析