Search code examples
javahttpclientvert.xvertx-httpclient

Vertx HttpClientRequest - Unable to catch timeout exception


I have been unable to catch time out exception that happens in my vertx HttpClientRequest. I have enclosed my connection and request creation code in try-catch block. Also I have added exceptionHandler and endHandler. But none of them gets fired when the time out happens. All I receive is the below error message which gets printed on the console. Please give me idea how to catch this exception, so that I can call the caller back with relevant info.

io.vertx.core.http.impl.HttpClientRequestImpl SEVERE: io.netty.channel.ConnectTimeoutException: connection timed out:

The code below is what I use to make request to server. As you can see I have used try-catch and added exceptionHandler as well.

try{
    HttpClient httpClient = Vert.x.createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true).setVerifyHost(false));
    HttpClientRequest request = httpClient.get(port, host, uri.getRawPath(), event-> {
        event.exceptionHandler(e -> {
            log.error(" Error:: " + e);
        });
        event.handler(handler -> {
            //code
        });
    });                             
    request.putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic "+authEnc);
    request.end();
} catch(Exception e){
    log.error(" Exception :: " + e);
}

Solution

  • Due to the async programing model you won't be able to use try-catch since your method has long been terminated before you get the timeout event. In order to catch it you need to setup an exception handler like:

    request.exceptionHandler(t -> {
      // where t is a throwable
      // do something with it...
    }
    

    If you're interested in catching response exceptions same concept applies.