You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在@ExceptionHandler中获取RestClientException对应的HttpRequest

如何在RestClient抛出异常时获取请求信息并格式化统一DTO?

我正在开发公司内部共享库,需要拦截所有异常并格式化为统一的DTO(已简化):

{
    "serviceName": "my-service-name",
    "errorCode": "ExternalRequestException",
    "externalServiceUrl": "http://external-service.com:8080/api/method-name?param=1",
    "externalErrorCode": "InvalidArgumentException",
    "externalErrorMessage": "Invalid argument param ....",
    "internalErrors": [],
}

处理WebClientRequestException或WebClientResponseException时没有问题,因为它们包含requestUrl或完整HttpRequest以获取请求目标URL。我可以按如下方式为WebClient添加org.springframework.web.reactive.function.client.ClientResponse#createException:

var response = webClient
            .get()
            .uri("http://external-service.com:8080/api/method-name?param=1")
            .retrieve()
            .onStatus(HttpStatusCode::isError, ClientResponse::createException)
            .bodyToMono(String.class)
            .block();

这样就能确保该调用抛出的WebClientRequestException或WebClientResponseException包含请求URL(示例中的http://external-service.com:8080/api/method-name?param=1)。

核心问题是:当RestClient抛出异常时,如何获取请求信息?或许需要开发类似RestClientInterceptor的组件,为标准异常补充请求特定信息。

更新

  • 初步调查:默认情况下异常在org.springframework.web.client.StatusHandler#defaultHandler中创建,该处理器上下文里可获取HttpRequest,但未被使用。这让人困惑,因为请求信息对4xx异常等场景很有用。
  • 已在spring-framework项目中提交Issue。

内容的提问来源于stack exchange,提问作者snej0keee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 16:39:51