RestTemplate ConnectException 无法访问

Jim*_*lor 5 rest resttemplate spring-boot request-mapping

我不明白这一点...我正在尝试捕获一个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());
    }
}
Run Code Online (Sandbox Code Playgroud)

捕获的异常是:

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
Run Code Online (Sandbox Code Playgroud)

如果未找到,我的下游将返回 404,如果下游离线,则productID显然会返回 a 。ConnectException我想做的就是将相关状态代码传递回浏览器。

我怎么做?

Bye*_*Bye 5

抓住ResourceAccessException。它隐藏ConnectExceptionRestTemplate.