【发布时间】:2018-04-13 15:02:35
【问题描述】:
我不明白这一点...我正在尝试捕获java.net.ConnectException,以防我的下游 API 离线。但是 Eclipse 警告我它无法访问 - 暗示代码不能抛出 ConnectException。但是,它显然可以。
@RequestMapping("/product/{id}")
public JsonNode getProduct(@PathVariable("id") int productID, HttpServletResponse oHTTPResponse)
{
RestTemplate oRESTTemplate = new RestTemplate();
ObjectMapper oObjMapper = new ObjectMapper();
JsonNode oResponseRoot = oObjMapper.createObjectNode();
try
{
ResponseEntity<String> oHTTPResponseEntity = oRESTTemplate.getForEntity("http://localhost:9000/product/"+productID, String.class);
}
catch (ConnectException e)
{
System.out.println("ConnectException caught. Downstream dependency is offline");
}
catch (Exception e)
{
System.out.println("Other Exception caught: " + e.getMessage());
}
}
捕获的异常是:
Other Exception caught: I/O error on GET request for "http://localhost:9000/product/9": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
如果未找到 productID,我的下游将返回 404,如果下游处于脱机状态,则显然返回 ConnectException。我要做的就是将相关的状态码传回浏览器。
我该怎么做?
【问题讨论】:
-
在带有“Exception”的 catch 块中检查异常的类型,看起来 ConnectException 被包装在另一个异常中......
标签: rest spring-boot resttemplate request-mapping