我不明白这个..。我正在尝试捕获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。我所要做的就是将相关的状态码传递回浏览器。
我该怎么做?
发布于 2018-09-11 16:14:05
抓住ResourceAccessException。它将ConnectException隐藏在RestTemplate中。
发布于 2020-05-16 08:56:05
RestTemplate类的内部方法链处理所有的IOException (它是ConnectException的超类)并抛出一个新的ResourceAccessException,因此,RestTemplate方法只能捕获ResourceAccessException类型或其层次结构树的异常。
https://stackoverflow.com/questions/47052421
复制相似问题