【发布时间】:2018-08-08 18:46:10
【问题描述】:
我创建了一个通用方法来调用外部 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));
【问题讨论】:
标签: java spring rest controller resttemplate