Spring Boot RestTemplate ConnectException Unreachable

huus2vyu  于 2024-01-06  发布在  Spring
关注(0)|答案(3)|浏览(182)

我不明白.

  1. @RequestMapping("/product/{id}")
  2. public JsonNode getProduct(@PathVariable("id") int productID, HttpServletResponse oHTTPResponse)
  3. {
  4. RestTemplate oRESTTemplate = new RestTemplate();
  5. ObjectMapper oObjMapper = new ObjectMapper();
  6. JsonNode oResponseRoot = oObjMapper.createObjectNode();
  7. try
  8. {
  9. ResponseEntity<String> oHTTPResponseEntity = oRESTTemplate.getForEntity("http://localhost:9000/product/"+productID, String.class);
  10. }
  11. catch (ConnectException e)
  12. {
  13. System.out.println("ConnectException caught. Downstream dependency is offline");
  14. }
  15. catch (Exception e)
  16. {
  17. System.out.println("Other Exception caught: " + e.getMessage());
  18. }
  19. }

字符串
捕获的异常是:

  1. 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
如果下游不可达,一种可能的处理方法(基于您的原始代码):

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

字符串

相关问题