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?
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.
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.
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.
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.
Catch ResourceAccessException
. It hides ConnectException
in RestTemplate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With