Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate ConnectException Unreachable

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?

like image 210
Jim Taylor Avatar asked Nov 01 '17 10:11

Jim Taylor


People also ask

How do you handle ConnectException?

ConnectException exception is one of the most common Java exceptions related to networking. We may encounter it when we're establishing a TCP connection from a client application to a server. As it's a checked exception, we should handle it properly in our code in a try-catch block.

How do you handle RestTemplate exception?

Default Error Handling By default, the RestTemplate will throw one of these exceptions in the case of an HTTP error: HttpClientErrorException – in the case of HTTP status 4xx. HttpServerErrorException – in the case of HTTP status 5xx. UnknownHttpStatusCodeException – in the case of an unknown HTTP status.

How do you use RestTemplate postForObject?

4.1. RestTemplate's postForObject method creates a new resource by posting an object to the given URI template. It returns the result as automatically converted to the type specified in the responseType parameter.

How do you use postForEntity RestTemplate?

Using postForEntity()Find the postForEntity method declaration from Spring doc. url: The URL to post the request. request: The object to be posted. responseType: The type of response body.


1 Answers

Catch ResourceAccessException. It hides ConnectException in RestTemplate.

like image 190
ByeBye Avatar answered Nov 03 '22 19:11

ByeBye