本文介绍了抛出RestClientException时如何检索HTTP状态代码和响应正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
RestTemplate
的方法,例如 postForEntity()
throw RestClientException
。我想从catch块中的异常对象中提取HTTP状态代码和响应主体。我该怎么做?
The methods of RestTemplate
such as postForEntity()
throw RestClientException
. I would like to extract the HTTP status code and response body from that exception object in the catch block. How can I do that?
推荐答案
而不是捕捉 RestClientException
,赶上特殊的 HttpClientErrorException
。
Instead of catching RestClientException
, catch the special HttpClientErrorException
.
以下是一个例子:
try {
Link dataCenterLink = serviceInstance.getLink("dataCenter");
String dataCenterUrl = dataCenterLink.getHref();
DataCenterResource dataCenter =
restTemplate.getForObject(dataCenterUrl, DataCenterResource.class);
serviceInstance.setDataCenter(dataCenter);
} catch (HttpClientErrorException e) {
HttpStatus status = e.getStatusCode();
if (status != HttpStatus.NOT_FOUND) { throw e; }
}
提供和分别获取状态代码和正文。
HttpClientErrorException
provides getStatusCode
and getResponseBodyAsByteArray
to get the status code and body, respectively.
这篇关于抛出RestClientException时如何检索HTTP状态代码和响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!