我不明白这一点...如果下游API离线,我正在尝试捕获java.net.ConnectException
。但是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
。我要做的就是将相关的状态代码传回浏览器。我怎么做?
最佳答案
捕获ResourceAccessException
。它将ConnectException
隐藏在RestTemplate
中。
关于rest - RestTemplate ConnectException无法访问,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47052421/