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

如何捕获Web Client中400 Bad Request的响应体?

捕获Web Client返回400 Bad Request时的响应体

Spring WebClient 处理方案

Spring WebClient默认会在收到4xx/5xx状态码时抛出WebClientResponseException,你可以通过捕获异常或主动处理状态码来获取响应体:

1. 同步调用场景

try {
    String normalResponse = webClient.get()
            .uri("目标请求地址")
            .retrieve()
            .bodyToMono(String.class)
            .block();
} catch (WebClientResponseException.BadRequest e) {
    // 获取400响应体字符串
    String errorBody = e.getResponseBodyAsString();
    // 也可以解析为自定义错误对象
    CustomErrorDto errorDto = e.getResponseBodyAs(CustomErrorDto.class);
    // 后续处理错误逻辑
}

2. 异步响应式场景

如果用Reactive模式(Mono/Flux),可以通过onStatus主动拦截400状态,避免抛出异常并直接读取响应体:

webClient.get()
        .uri("目标请求地址")
        .retrieve()
        .onStatus(status -> status == HttpStatus.BAD_REQUEST, clientResponse -> {
            return clientResponse.bodyToMono(String.class)
                    .flatMap(errorBody -> {
                        // 可封装为自定义异常抛出,或直接处理
                        return Mono.error(new CustomBadRequestException(errorBody));
                    });
        })
        .bodyToMono(String.class)
        .subscribe(
                normalResp -> { /* 处理正常响应 */ },
                error -> {
                    if (error instanceof CustomBadRequestException) {
                        String errorBody = ((CustomBadRequestException) error).getErrorBody();
                        // 处理400错误内容
                    }
                }
        );

通用Web Client 处理思路

不管使用哪种Web Client类库,核心逻辑一致:

  • 关闭或绕过默认的错误抛出机制
  • 检查响应状态码,当状态为400时读取响应体
  • 将响应体解析为字符串或自定义对象处理

以Apache HttpClient为例:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("目标请求地址");

try (CloseableHttpResponse response = httpClient.execute(request)) {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_BAD_REQUEST) {
        // 读取400响应体
        String errorBody = EntityUtils.toString(response.getEntity());
        // 执行错误处理逻辑
    } else {
        // 处理正常响应
    }
} catch (IOException e) {
    // 处理IO异常
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:37:25