RestTemplate服务端异常信息无法完整打印

问题:

		...
	    try {
            res = restTemplate.postForObject(url.toString(), requestEntity, String.class);
        } catch (RestClientException e){
            logger.error("出现异常 {}", e.getMessage(), e);
        }
		...

原来用的RestClientException进行捕获,打印错误信息,一直只有个500,没有其他详细信息,后面偶然用了下postman调用,发现还有服务端的返回的其他信息。

解决方案:

进行debug调试后,发现里面返回的ClientHttpResponse里面是有完整的返回信息,只是RestClientException没有获取方法,后面从网上看到有用HttpClientErrorException来捕获后台打印完整信息,然后找到了RestClientException的子类RestClientResponseException,其中提供了获取responseBody信息的接口,从而可以打印完整信息

		...
	    try {
            res = restTemplate.postForObject(url.toString(), requestEntity, String.class);
        } catch (RestClientResponseException e){
            logger.error("出现异常 {} ", e.getResponseBodyAsString(), e);
        } catch (Exception e){
            logger.error("出现异常 {}", e.getMessage(), e);
        }
		...
在使用 RestTemplate 进行请求时,可能会遇到一些异常情况,需要进行异常处理。常见的异常包括: 1. HttpServerErrorException:当服务端返回 4xx 或 5xx 的 HTTP 状态码时,RestTemplate 会抛出 HttpServerErrorException。可以通过捕获该异常来处理服务端返回的错误信息。 ```java try { ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); // 处理正常情况下的响应 } catch (HttpServerErrorException e) { // 处理服务端返回的错误信息 System.out.println("Server error: " + e.getStatusCode() + " - " + e.getResponseBodyAsString()); } catch (RestClientException e) { // 其他 RestClientException 异常的处理 } ``` 2. ResourceAccessException:当发生网络连接问题或超时时,RestTemplate 可能会抛出 ResourceAccessException 异常。可以通过捕获该异常来处理网络异常。 ```java try { ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, null, String.class); // 处理正常情况下的响应 } catch (ResourceAccessException e) { // 处理网络异常 System.out.println("Network error: " + e.getMessage()); } catch (RestClientException e) { // 其他 RestClientException 异常的处理 } ``` 除了上述两种常见的异常,还可能会遇到其他异常,如 HttpClientErrorException(当服务端返回 4xx 的 HTTP 状态码时)、UnknownHttpStatusCodeException(当服务端返回不明确的 HTTP 状态码时)等。根据具体需求,可以捕获相应的异常并进行处理。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值