在 sleuth + zipkin 链路追踪中,可通过 tracer.currentspan().tag("error.code", errorcode) 在异常捕获处手动添加 errorcode tag,需确保 span 未关闭且上下文有效,标记后可在 zipkin ui 的 tags 中查看并支持按 error.code 过滤。

在 Sleuth + Zipkin 的链路追踪中,自定义异常的 errorCode 可以通过手动向当前 Span 添加 Tag 的方式传递到 Zipkin,从而在 UI 中查看或用于后续分析。关键在于:异常发生时,Span 仍处于活跃状态(未 close),且你有对 Tracer 或 Span 的访问权限。
在异常捕获处显式添加 errorCode Tag
最直接的方式是在业务代码中捕获自定义异常后,获取当前 Span 并写入 Tag:
- 使用
tracer.currentSpan()获取当前活跃 Span(注意判空) - 调用
span.tag("error.code", errorCode)写入自定义错误码 - 建议同时设置
span.tag("error", "true")保持与标准错误标记一致
示例:
try {
doSomething();
} catch (MyBizException e) {
Span current = tracer.currentSpan();
if (current != null) {
current.tag("error.code", e.getErrorCode());
current.tag("error", "true");
current.tag("error.message", e.getMessage());
}
throw e;
}
统一异常处理器中注入 Span(Spring Boot 场景)
若项目使用全局 @ControllerAdvice 处理异常,可在处理器中访问 Tracer:
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
- 注入
Tracer实例 - 在
@ExceptionHandler方法中获取当前 Span - 避免在异步线程或已关闭的 Span 上操作(Sleuth 默认不跨线程传播 Span,需确保上下文存在)
示例:
@RestControllerAdvice
public class GlobalExceptionHandler {
private final Tracer tracer;
public GlobalExceptionHandler(Tracer tracer) {
this.tracer = tracer;
}
@ExceptionHandler(MyBizException.class)
public ResponseEntity<string> handleBizError(MyBizException e) {
Span current = tracer.currentSpan();
if (current != null) {
current.tag("error.code", e.getErrorCode());
current.tag("error", "true");
}
return ResponseEntity.badRequest().body(e.getMessage());
}
}</string>
避免 Span 已结束导致 tag 失效
Sleuth 默认会在 Web 请求结束时自动 close 当前 Span。若异常发生在请求后期(如 filter 链尾、afterCompletion 回调中),Span 可能已被关闭:
- 确认添加 Tag 的时机早于 Span close —— 推荐在业务逻辑层或 Controller 层捕获并标记
- 不要依赖
HttpServletResponse的setStatus(5xx)自动标记:它只设http.status_code和error,不识别你的errorCode - 如需更底层控制,可考虑使用
Tracer.withSpanInScope()临时激活 Span,但通常不必要
Zipkin 查看与过滤建议
标记成功后,error.code 会作为 binary annotation 出现在 Zipkin 的 Span Detail 中:
- Zipkin UI 的 “Tags” 标签页下可见
error.code: xxx - 可通过 Zipkin 查询参数
annotationQuery=error.code%3D1001过滤指定错误码的链路 - 如需告警或聚合分析,可在 Zipkin 数据导出(如 Kafka/S3)后按该 Tag 提取指标
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










