news 2026/8/11 14:14:40

简单业务异常类

作者头像

张小明

前端开发工程师

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/8/10 6:40:42

5分钟掌握RichTextKit:SwiftUI富文本编辑器终极指南

5分钟掌握RichTextKit&#xff1a;SwiftUI富文本编辑器终极指南 【免费下载链接】RichTextKit RichTextKit is a Swift-based library for working with rich text in UIKit, AppKit and SwiftUI. 项目地址: https://gitcode.com/gh_mirrors/ri/RichTextKit 还在为Swift…

作者头像 李华
网站建设 2026/8/9 22:49:08

如何有效准备编程竞赛?五个阶段科学备考方法

如何有效准备编程竞赛?五个阶段科学备考方法 与一位初中生家长交流时,她提到:“孩子学编程有段时间了,想参加竞赛却不知如何准备,考过GESP但感觉基础不牢,NCT是否更适合长期学习?” 事实上,编程竞赛的准备并非短期冲刺,而是一个循序渐进的系统过程——如同建造房屋,…

作者头像 李华
网站建设 2026/8/10 17:46:48

BG3模组管理器终极指南:5分钟快速上手博德之门3模组管理

BG3模组管理器终极指南&#xff1a;5分钟快速上手博德之门3模组管理 【免费下载链接】BG3ModManager A mod manager for Baldurs Gate 3. 项目地址: https://gitcode.com/gh_mirrors/bg/BG3ModManager 想要在《博德之门3》中体验更多精彩内容&#xff1f;BG3模组管理器就…

作者头像 李华
网站建设 2026/8/10 12:43:05

6、黑客必备:Linux 网络技能与软件管理

黑客必备:Linux 网络技能与软件管理 1. 基础 Linux 网络技能概述 在网络操作中,黑客需要具备一些基本的 Linux 网络技能,用于连接、分析和管理网络。随着技术的不断进步,这些技能在侦察、欺骗和连接目标系统等方面会变得越来越有用。在深入学习之前,我们可以通过完成以下…

作者头像 李华
网站建设 2026/8/10 17:46:48

Font Awesome 7全面解析:现代化图标解决方案的革新之路

Font Awesome 7全面解析&#xff1a;现代化图标解决方案的革新之路 【免费下载链接】Font-Awesome The iconic SVG, font, and CSS toolkit 项目地址: https://gitcode.com/GitHub_Trending/fo/Font-Awesome 在当今快速发展的前端开发领域&#xff0c;图标作为用户界面的…

作者头像 李华
网站建设 2026/8/10 13:28:52

MySQL业务数据量增长到单表成为瓶颈时,该如何做?

文章目录引言&#xff1a;单表瓶颈的原因一、第一阶段&#xff1a;应急与优化1.1 SQL与索引优化&#xff08;首要任务&#xff09;1.2 表结构设计优化1.3 引入缓存&#xff1a;为数据库减负二、第二阶段&#xff1a;架构升级2.1 读写分离&#xff1a;分担读压力2.2 数据库分区&…

作者头像 李华