RestControllerAdvice响应的定制

后端开发 2026-07-07

org.springframework.web.bind.annotation.ControllerAdvice 添加头信息很容易,因为它可以返回 ResponseEntity<ErrorMessage>,例如:

new ResponseEntity<ErrorMessage>(message, httpHeaders, HttpStatus.NOT_FOUND);

但是如何把例如 traceId 这样的指标添加到 org.springframework.web.bind.annotation.RestControllerAdvice 的响应中呢?这可能吗?

解决方案

是的,完全可以。

@RestControllerAdvice 只是 @ControllerAdvice + @ResponseBody 的一个快捷方式。它完全支持返回带有自定义头信息的 ResponseEntity,并且Spring仍然会自动将主体序列化为JSON。

下面是将 traceId 添加到 响应头 的方法:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorMessage> handleNotFound(ResourceNotFoundException ex) {
        ErrorMessage message = new ErrorMessage(ex.getMessage());

        // Get your traceId (e.g., from MDC or your tracing library)
        String traceId = MDC.get("traceId"); 

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Trace-Id", traceId);

        return new ResponseEntity<>(message, headers, HttpStatus.NOT_FOUND);
    }
}

或者,如果你想让 traceId 出现在 JSON正文 中,只需在你的 ErrorMessage 类中添加一个 traceId 字段并直接返回它:

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND) 
public ErrorMessage handleNotFound(ResourceNotFoundException ex) {
    String traceId = MDC.get("traceId");
    return new ErrorMessage(ex.getMessage(), traceId);
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章