我创建了一个通用方法来调用外部API(调用后)。如果外部rest API返回2 **,一切工作正常,但是如果发生任何错误,则会引发异常。
这4 **响应不能像正常答案一样对待,而不是产生异常吗?问题是我需要获取错误消息(响应正文)并将其发送回调用方。
这是我的代码:
public ResponseEntity<String> post(String api, Map<String, Object> data) {
ResponseEntity<String> response = new ResponseEntity<String>(HttpStatus.OK);
try {
StopWatch stopwatch = new StopWatch();
stopwatch.start();
log.debug("post(): " + host + "/" + api );
// Set the headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// Convert the Map to Gson
Gson gson = new Gson();
String json = gson.toJson(data);
// Call the API
HttpEntity<?> request = new HttpEntity<>(json, headers);
response = new RestTemplate().postForEntity(host + "/" + api, request, String.class);
stopwatch.split();
log.info("All request completed [" + response.getStatusCode() + "] in " + stopwatch.getSplitTime());
return response;
} catch (Exception ex) {
log.error(ex);
throw new RuntimeException();
}
}
如果发生错误,外部API将返回以下内容:
ResponseEntity<Integer> response = new ResponseEntity<Integer>();
[.. business code ..]
res.setResponse(new ResponseEntity<String>(CommonValue.userNotFound, HttpStatus.UNAUTHORIZED));
答案 0 :(得分:0)
使用RestTemplate#exchange(..)方法返回ResponseEntity。这不会引发异常,但会将答案解析到ResponseEntity中,您可以在其中检索状态代码等。