那么使用restTemplate 的情况下,如果postForObject方法抛出了异常,那么在catch块中还能拿到 response 的完整信息吗

在使用 RestTemplate 的情况下,调用如 postForObject() 方法时,如果抛出了异常,比如 HTTP 4xxHTTP 5xx 状态码导致的异常,默认情况下,异常中不会直接包含完整的 HTTP 响应体(response body)。然而,RestTemplate 抛出的异常类确实包含了部分响应信息,比如状态码和响应头。

通常,如果 postForObject() 方法抛出异常,它会抛出一个 HttpClientErrorExceptionHttpServerErrorException,这些异常类可以让你访问到响应的状态码、响应头和响应体。

1. 如何捕获异常并获取响应信息?

通过捕获 RestClientResponseException(它是 HttpClientErrorExceptionHttpServerErrorException 的父类),你可以获取到完整的响应信息。

示例代码:

import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {

    private RestTemplate restTemplate = new RestTemplate();

    public void makePostRequest() {
        String url = "https://example.com/api/resource";
        String requestBody = "{\"name\":\"test\"}";

        try {
            // 发送 POST 请求
            String response = restTemplate.postForObject(url, requestBody, String.class);
            System.out.println("Response: " + response);
        } catch (RestClientResponseException e) {
            // 捕获异常并获取完整的响应信息
            HttpStatus statusCode = e.getStatusCode();
            String responseBody = e.getResponseBodyAsString();
            System.out.println("HTTP Status Code: " + statusCode);
            System.out.println("Response Body: " + responseBody);
        }
    }
}

2. 解释代码:

  • postForObject():发送一个 POST 请求,并期望返回响应体作为 String
  • RestClientResponseException:当 RestTemplate 抛出异常时,这个异常类允许你访问状态码和响应体。具体来说,HttpClientErrorException(4xx 错误)和 HttpServerErrorException(5xx 错误)都是 RestClientResponseException 的子类,代表客户端和服务端的错误。
  • getResponseBodyAsString():这个方法可以让你捕获到异常时的完整响应体。
  • getStatusCode():可以获取 HTTP 状态码,例如 404500

输出示例(假设服务端返回 400 Bad Request):

HTTP Status Code: 400 BAD_REQUEST
Response Body: {"error": "Invalid input"}

3. 捕获不同类型的异常:

  • HttpClientErrorException:用于捕获 4xx 错误(客户端错误)。
  • HttpServerErrorException:用于捕获 5xx 错误(服务器错误)。
  • RestClientException:用于捕获其他客户端错误,比如连接问题、超时等。

你可以根据需要对不同类型的异常进行不同的处理:

try {
    String response = restTemplate.postForObject(url, requestBody, String.class);
} catch (HttpClientErrorException e) {
    System.out.println("Client Error: " + e.getStatusCode());
    System.out.println("Response Body: " + e.getResponseBodyAsString());
} catch (HttpServerErrorException e) {
    System.out.println("Server Error: " + e.getStatusCode());
    System.out.println("Response Body: " + e.getResponseBodyAsString());
} catch (RestClientException e) {
    System.out.println("Other Error: " + e.getMessage());
}

总结:

  • RestTemplate 中,如果 postForObject() 抛出了异常(如 4xx 或 5xx 错误),你可以通过捕获 RestClientResponseException 或其子类 HttpClientErrorExceptionHttpServerErrorException 来获取完整的响应信息,包括状态码和响应体。
  • RestClientResponseException 提供了方法 getResponseBodyAsString() 来获取响应体内容,以及 getStatusCode() 来获取状态码。

这让你在处理异常时可以更细粒度地获取和处理响应信息。

posted @   gongchengship  阅读(150)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示