异常消息必须包含可定位的上下文,如订单ID、用户ID、接口路径等业务标识,并用具体动作和值替代模糊动词,避免拼接敏感信息、运行时调用易错方法或在getMessage()中塞入堆栈。
Java里抛出的异常如果只写 "Error occurred" 这类泛化信息,排查时根本无法判断是哪个请求、哪条数据、哪个参数出了问题。关键不是“报错了”,而是“在哪错、因何错、谁触发的”。
"Failed to process order #ORD-2025-7890: payment amount is negative"
"parseDate('2025-13-01') failed: month must be 1–12"
"user_id=usr_8a2b...f3e1"
异常构造阶段不该调用可能失败的方法,比如 new IllegalArgumentException("User " + user.getName() + " not found") 中,若 user.getName() 抛空指针,原始错误就被掩盖了。
Objects.toString(user, "null")
安全转换JSON.stringify()、LocalDateTime.now().toString() 等易出错或带副作用的操作getMessage() 和日志记录内容异常消息面向开发者调试,日志行面向运维监控,二者职责不同。很多团队把完整堆栈塞进 getMessage(),导致日志重复且难以结构化解析。
getMessage() 只保留「一句话因果」:如 "Cannot update status from 'PAID' to 'CANCELLED'"
logger.error("Update status rejected", e)
toString() 吗?一般不用。JDK 默认的 toString() 已包含类名 + 消息 + 堆栈缩略,够用。强行重写反而破坏标准行为,让 printStackTrace() 或 APM 工具解析异常时丢失关键信息。
toSummary() 辅助方法,由调用方按需调用toString() 中抛异常、访问数据库或远程服务 —— 这会导致 printStackTrace() 自身崩溃public class OrderStatusTransitionException extends RuntimeException {
private final String orderId;
private final String fromStatus;
private final String toStatus;
public OrderStatusTransitionException(String orderId, String from, String to) {
super(String.format("Cannot transition order %s from '%s' to '%s'", orderId, from, to));
this.orderId = orderId;
this.fromStatus = from;
this.toStatus = to;
}
// 不重写 toString(),保持默认行为
public String toSummary() {
return String.format("[OrderStatus] %s: %s → %s", orderId, fromStatus, toStatus);
}
}
异常消息最常被忽略的一点:它不是给人“读得顺”的,而是给机器和人一起“查得准”的。多一个订单号,少一次grep;少一次运行时拼接,多一分堆栈可信度。