设计业务异常类需要继承 runtimeexception 并实现 serializable,核心是封装错误码和错误信息。通过定义常量或枚举来统一管理业务状态码,并在构造函数中调用父类构造器传递消息。这样可以在捕获异常时直接获取结构化数据,便于前端展示或日志记录。

如何构建支持多态的错误码体系
使用枚举类作为错误码载体,将错误码、描述信息和HTTP状态码绑定在一起。在自定义异常类中增加一个 getErrorCode() 方法返回该枚举实例。这种设计避免了硬编码字符串,提高了代码的可维护性和类型安全性。

public enum BizErrorCode {
USER_NOT_FOUND(1001, "用户不存在", 404),
PARAM_ERROR(1002, "参数校验失败", 400);
private final int code;
private final String message;
private final int httpStatus;
BizErrorCode(int code, String message, int httpStatus) {
this.code = code;
this.message = message;
this.httpStatus = httpStatus;
}
public int getCode() { return code; }
public String getMessage() { return message; }
public int getHttpStatus() { return httpStatus; }
}
如何处理异常链与堆栈追踪
在构造函数中必须调用 super(message, cause) 以保留原始异常堆栈。当业务逻辑抛出底层异常(如数据库异常)时,应将其包装为业务异常向上层传递。这确保了调试时能追溯到根本原因,同时对外屏蔽了技术细节。
立即学习“Java免费学习笔记(深入)”;

public class BusinessException extends RuntimeException {
private final BizErrorCode errorCode;
public BusinessException(BizErrorCode errorCode) {
super(errorCode.getMessage());
this.errorCode = errorCode;
}
public BusinessException(BizErrorCode errorCode, Throwable cause) {
super(errorCode.getMessage(), cause);
this.errorCode = errorCode;
}
public BizErrorCode getErrorCode() {
return errorCode;
}
}
基于具体输入条件如何触发特定异常
当传入的用户ID为负数时,程序会抛出 BizException 并携带 PARAM_ERROR 错误码。此时 getCause() 返回 null,因为未提供原始异常对象。开发者可通过 getErrorCode().getCode() 获取整型错误码 1002,用于统一响应处理。


















