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

Spring Boot中使用RestTemplate调用跨服务接口如何捕获错误响应

问题原因

RestTemplate 自带的默认响应错误处理器 DefaultResponseErrorHandler 会将HTTP状态码为4xx(客户端错误,你遇到的404就属于这类)和5xx(服务端错误)的响应统一封装为对应异常抛出,不会正常返回ResponseEntity对象,所以你无法直接拿到REST-B返回的错误信息。

解决方案

方案1:捕获特定异常提取错误信息

直接在异常捕获分支针对性处理HttpClientErrorException,从异常中可以直接获取状态码、响应头、响应体内容:

try {
    ResponseEntity<String> response = restTemplate.exchange(
            searchurl,
            HttpMethod.GET,
            request,
            String.class
    );
    // 处理2xx成功响应的逻辑
    String body = response.getBody();
    HttpStatus status = response.getStatusCode();
    // 后续业务处理
} catch (HttpClientErrorException e) {
    // 处理4xx类错误
    HttpStatus errorStatus = e.getStatusCode();
    String errorBody = e.getResponseBodyAsString();
    // 可拿到REST-B返回的完整错误信息,自行做业务处理
    if (errorStatus == HttpStatus.NOT_FOUND) {
        // 客户不存在的业务逻辑
    }
} catch (HttpServerErrorException e) {
    // 处理5xx类错误
    String serverErrorBody = e.getResponseBodyAsString();
    // 服务端错误的业务处理
} catch (Exception e) {
    // 其他异常处理,比如连接超时、域名解析失败等
    e.printStackTrace();
}

方案2:自定义响应错误处理器,关闭非2xx状态码抛异常的逻辑

如果希望不管响应状态码是多少,都正常返回ResponseEntity自行判断处理,可以自定义ResponseErrorHandler替换默认实现:

// 自定义错误处理器
public class NoOpResponseErrorHandler implements ResponseErrorHandler {
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        // 直接返回false,告诉RestTemplate所有响应都不算错误,不会抛异常
        return false;
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        // 因为hasError永远返回false,这个方法不会被调用,留空即可
    }
}

然后在创建RestTemplate的时候注入这个处理器:

RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());

// 后续调用exchange的时候不管状态码是多少都会正常返回ResponseEntity
ResponseEntity<String> response = restTemplate.exchange(
        searchurl,
        HttpMethod.GET,
        request,
        String.class
);

// 自行判断状态码处理即可
if (response.getStatusCode().is2xxSuccessful()) {
    // 处理成功逻辑
} else if (response.getStatusCode() == HttpStatus.NOT_FOUND) {
    // 处理客户不存在逻辑
} else {
    // 其他错误处理
}

额外优化建议

你当前请求头里手动设置了Content-Length: 65,这个配置不合理:GET请求本身没有请求体,不需要设置Content-Type和Content-Length,硬编码长度反而可能导致请求异常,建议删掉这两个头的设置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:24:05