Java中应通过枚举类统一管理错误码,每个枚举项封装错误码、提示语和HTTP状态码,并实现IErrorCode接口;按模块分段编号(如1xxx用户),配合BizException与@ControllerAdvice实现标准化异常处理。

Java中不推荐直接用整数或字符串硬编码错误码,而应通过枚举类统一管理。每个枚举项代表一个明确的业务异常场景,自带错误码、提示语、HTTP状态码(可选)等属性,便于维护、国际化和统一处理。
先设计一个通用接口,约束所有错误码枚举必须实现的基本能力:
示例接口:
public interface IErrorCode {
int getCode();
String getMsg();
int getHttpStatus();
}让枚举实现上述接口,按模块或功能分组定义。例如用户模块:
立即学习“Java免费学习笔记(深入)”;
public enum UserErrorCode implements IErrorCode {
USER_NOT_FOUND(1001, "用户不存在", HttpStatus.NOT_FOUND.value()),
USER_DISABLED(1002, "账号已被禁用", HttpStatus.FORBIDDEN.value()),
PASSWORD_ERROR(1003, "密码错误", HttpStatus.UNAUTHORIZED.value()),
MOBILE_INVALID(1004, "手机号格式不合法", HttpStatus.BAD_REQUEST.value());
private final int code;
private final String msg;
private final int httpStatus;
UserErrorCode(int code, String msg, int httpStatus) {
this.code = code;
this.msg = msg;
this.httpStatus = httpStatus;
}
@Override
public int getCode() { return code; }
@Override
public String getMsg() { return msg; }
@Override
public int getHttpStatus() { return httpStatus; }
}关键点:
– 错误码数值建议按模块分段(如1xxx用户,2xxx订单,3xxx支付)
– 枚举名语义清晰,见名知意
– 提示语避免暴露敏感信息(如不写“密码是123456”)
在Spring Boot中,用@ControllerAdvice捕获自定义异常,再根据枚举输出标准化响应:
@ExceptionHandler(BizException.class)
@ResponseBody
public Result<?> handleBizException(BizException e) {
IErrorCode errorCode = e.getErrorCode();
return Result.fail(errorCode.getCode(), errorCode.getMsg());
}其中BizException是一个运行时异常,构造时传入枚举实例:
throw new BizException(UserErrorCode.USER_NOT_FOUND);
这样整个链路就打通了:抛异常 → 拿枚举 → 取码和提示 → 统一返回。
基本上就这些。枚举错误码不是炫技,而是让错误可读、可查、可追踪。只要接口约定清楚、分组合理、团队遵守,维护成本很低,但收益明显。
以上就是Java异常如何自定义枚举错误码_Java错误码体系编写方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号