Spring Boot RestTemplate ConnectException Unreachable

huus2vyu  于 5个月前  发布在  Spring
关注(0)|答案(3)|浏览(60)

我不明白.

@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。我所要做的就是将相关的状态代码传递回浏览器。
我该怎么做呢?

wh6knrhe

wh6knrhe1#

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

euoag5mw

euoag5mw2#

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

dgenwo3n

dgenwo3n3#

正如前面提到的,RestTemplate#getForEntity()调用句柄IOException,所以不能直接捕获它。
如果您查看RestTemplate示例抛出的ResourceAccessException,您可以看到cause字段中有您要查找的ConnectionException
如果下游不可达,一种可能的处理方法(基于您的原始代码):

try {
    ResponseEntity<String> oHTTPResponseEntity = oRESTTemplate.getForEntity("http://localhost:9000/product/" + productID, String.class);
} catch (Exception e) {
    if (e.getCause() instanceof ConnectException) {
        System.out.println("ConnectException caught. Downstream dependency is offline");
    } else {
        System.out.println("Other Exception caught: " + e.getMessage());
    }
}

字符串

相关问题