Search code examples
javaspringrestspring-mvcresttemplate

Obtaining exception from rest service in string variable


I have this JSON request framed in Java. I will be hitting a rest template with my URL and this request.

{  
   "searchRequest":{  
      "header":{  
         "agency":"1111",
         "agent":"2222";
         "from":"0";
         "size":"15"
      },
      "requestParam":{  
         "firstName":"JOHN",
         "lastName":"PAK",
         "dob":"",
         "driverLicense":"",
         "membershipNumber":"",
         "phoneNumbers": "null",
         "addresses":"null"

      }
   }
}

CASE 1: Whenever I get a successful response, I get the same JSON which my rest template gives in the response variable.

public @ResponseBody String mpdValidate(@RequestBody String inputRequest, @RequestHeader String url)
            throws JsonParseException, JsonMappingException, IOException, JSONException {
        System.out.println(inputRequest);
        System.out.println(url);

        String response = null;

            if (url == null || url.isEmpty()) {
                url = "myURL";
            }

            try {
                HttpHeaders headers = new HttpHeaders();
                headers.set("X-ApplicationContext",
                        "{\"userId\":\"user\",\"transactionType\":\"realtime\",\"application\":\"app\",\"subSystem\":\"mpd\",\"address\":\"1.0.0.0\",\"correlationId\":\"0f333c\"} ");
                HttpEntity<String> request = new HttpEntity<String>(inputRequest, headers);

                response = restTemplate.postForObject(url, request, String.class);

            } catch (Exception e) {
                response = e.getMessage();
            }

        return response;
    }

CASE 2: And when there is a wrong request framed and there is a failed response, the rest template returns this response.

{
   "httpCode": 400,
   "httpMessage": "Bad Request",
   "moreInformation": "Request parameter is null",
   "timeStamp": 1539072063795
}

But the response variable returns null and enters to catch block throwing null pointer exception.

I want the above JSON in string format to my response variable.

Can someone help?


Solution

  • try {
        // ...
    } catch (HttpClientErrorException expection) {
        response = expection.getResponseBodyAsString();
    }
    

    You need to handle HttpClientErrorException (or its parent RestClientResponseException) and extract the response by HttpClientErrorException#getResponseBodyAsString.