5

I don't understand this... I'm trying to catch a java.net.ConnectException in case my downstream API is offline. However Eclipse warns me that it's unreachable - suggesting the code cannot throw a ConnectException. However, it clearly can.

@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());
    }
}

The exception caught is:

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

My downstream returns a 404 if the productID is not found and clearly a ConnectException if the downstream is offline. All I want to do is pass relevant status codes back to the browser.

How do I do that?

Jim Taylor
  • 111
  • 2
  • 10
  • In your catch block with "Exception" check the type of exception, looks like the ConnectException is wrapped inside another exception... – mrkernelpanic Nov 01 '17 at 10:45

2 Answers2

5

Catch ResourceAccessException. It hides ConnectException in RestTemplate.

ByeBye
  • 6,650
  • 5
  • 30
  • 63
0

The internal method chain of RestTemplate class handles all IOException (which is a superclass of ConnectException) and throws a new ResourceAccessException, therefore, RestTemplate methods only can catch exceptions of type ResourceAccessException or its hierarchy tree.

apolo884
  • 31
  • 3