【问题标题】:RestTemplate ConnectException UnreachableRestTemplate ConnectException 无法访问
【发布时间】: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


【解决方案1】:

RestTemplate 类的内部方法链处理所有 IOException(它是 ConnectException 的超类)并抛出一个新的 ResourceAccessException,因此,RestTemplate 方法只能捕获 ResourceAccessException 类型或其层次结构树的异常。

【讨论】:

    【解决方案2】:

    捕捉ResourceAccessException。它将ConnectException 隐藏在RestTemplate 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 2019-10-19
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多