Search code examples
spring-cloud-sleuthzipkinexceptionhandler

Sleuth/zipkin with ControllerAdvice is not working


I found there is an old issue Sleuth/Zipkin tracing with @ControllerAdvice, but I meet the same problem with the latest version(spring-cloud-starter-zipkin:2.1.0.RELEASE), I debug it and find that the error is null, so zipkin just guess with statuscode. I have to throw the exception again to make zipkin notify the exception

error is null

zipkin result

ControllerAdvice

throw the exception again, it works


Solution

  • It makes perfect sense that it's null. That's because YOU control the way what happens with the caught exception. In your case, nothing, cause you swallow that exception.

    If you want to do sth better, just add the error tag manually via the SpanCustomizer. That way you'll add the exception to the given span. It will then automatically get closed and reported to Zipkin (you can do sth else than ex.toString() of course.

    @Slf4j
    @RestControllerAdvice
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class ExceptionHanders {
    
        private final SpanCustomizer customizer;
    
        public ExceptionHanders(SpanCustomizer customizer) {
            this.customizer = customizer;
        }
    
        @ExceptionHandler({RuntimeException.class})
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public String handleRuntimeException(Exception ex) throws Exception {
            this.customizer.tag("error", ex.toString());
            return "testabcd";
        }
    }