-3

I have below code use to POST JSON object to the following URL

        HttpEntity messageEntity = new HttpEntity(message, buildHttpHeaders(getTerminalId()));
        String theUrl = "http://123.433.234.12/receive";
        try {
               System.out.println("In try block");
               ResponseEntity<Dto> responseEntity= restTemplate.exchange(theUrl, HttpMethod.POST, messageEntity, Dto.class);
          } catch (HttpStatusCodeException ex) {
              // get http status code
          }

If the URL is invalid or service unavailable, I want it throw error status code like 404 or 503. Unfortunatelly it will always stop at the try block..Is there a way to solve that ?

Output

In try block

Edit

 String theUrl = "http://123.433.234.12/receive" + transactionId; //invalid Id
   try {
          System.out.println("=========start=========");
          ResponseEntity<Dto> responseEntity= restTemplate.exchange(theUrl, HttpMethod.POST, messageEntity, Dto.class);
          System.out.println("=========end=========");
       } catch (HttpStatusCodeException ex) {
          String a = ex.getStatusCode().toString();
          System.out.println(a);
    }

Output

=========start=========
2017-09-22 14:54:54 [xles-server-ThreadPool.PooledThread-0-running] ERROR c.r.abc.jpos.JposRequestListener - Error HttpStatusCode 500org.springframework.web.client.HttpServerErrorException: 500 null

It stop and not display ========end ======== or any status code in catch block

Valid url

   http://abc0/receive/hello

If I change to

 http://abc0/recei/hello

I will get 404 in catch block, it look fine. But when I change to another url that not exits,example

 http://123.433.234.12/receive

it is in try block .Why ????

John Joe
  • 12,412
  • 16
  • 70
  • 135
  • If an exception is thrown, it will be in catch block... What another way are you asking?? – Mehraj Malik Sep 22 '17 at 05:15
  • You mean [this](https://stackoverflow.com/questions/28902374/spring-boot-rest-service-exception-handling/30193013#30193013)? – soorapadman Sep 22 '17 at 05:15
  • @MehrajMalik It in the try block – John Joe Sep 22 '17 at 05:17
  • @soorapadman tried that too – John Joe Sep 22 '17 at 05:17
  • 1
    @JohnJoe In the original question (non edited) you mentioned: "I want it throw error status code like 404 or 503". Answers were given keeping that in mind. Then you downvote the answer because you wanted to handle other error codes as well? You should have mentioned it clearly in the first place! – Yogesh Badke Sep 23 '17 at 06:45

2 Answers2

1

With reference to this doc, you should catch RestClientException instead of just HttpStatusCodeException.

If you want to throw exception in specific scenarios you can do it like this

    try {
        restTemplate.exchange(...);
    }
    catch (RestClientException e) {
        // implies error is related to i/o. 
        if (e instanceof ResourceAccessException) {
            // java.net.ConnectException will be wrapped in e with message "Connection timed out".
            if (e.contains(ConnectException.class)) {
                // handle connection timeout excp
            }
        } else if (e instanceof HttpClientErrorException) {
            // Handle all HTTP 4xx error codes here;

        } else if (e instanceof HttpServerErrorException) {
            // Handle all HTTP 5xx error codes here
        }
    }

for HttpClientErrorException you can get error code from excption as shown below

HttpClientErrorException clientExcp = (HttpClientErrorException) e;
HttpStatus statusCode = clientExcp.getStatusCode();

like wise, you could get error code for HttpServerErrorException.

Yogesh Badke
  • 4,249
  • 2
  • 15
  • 23
1

As far as I remember RestTemplate.exchange method throws RestClientException. You have HttpStatusCodeException in your catch clause, which is only one of RestClientException subclasses. The address you're trying to reach (http://123.433.234.12/receive) is not valid address, therefore you can't get ANY response from it (no 200s but no 500s or 400s too). Try to catch RestClientException and print its message to see what is going on. Then you can write some code to manage such situations.

Moreover if that does not work, try to go step by step and check wether ResponseEntity is null and what it has in its body. That's what I'm doing when I try to understand some method ;=)

  • I use `RestClientException` and it still stop at `=========start=========` – John Joe Sep 23 '17 at 02:18
  • After few seconds I get `org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://123.433.234.12/receive": Connection timed out (Connection timed out); nested exception is java.net.ConnectException: Connection timed out (Connection timed out)`. Is there a way I can handle the exception ? – John Joe Sep 23 '17 at 02:22