RestTemplate的方法如postForEntity()抛出RestClientException.我想从catch块中的异常对象中提取HTTP状态代码和响应主体.我怎样才能做到这一点? 捕获特殊的HttpClientErrorException,而不是捕获RestClient
这是一个例子:
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
分别提供getStatusCode
和getResponseBodyAsByteArray
获取状态代码和正文.