I'm trying to implement a Rest call to an authentication server using RestTemplate and log the response in case the server returns an exception. In order to do this, I used a ResponseEntityExceptionHandler to handle HttpClientErrorException's and HttpServerErrorException's.
public Response sendRequest(Request requestBody, String url, HttpMethod httpMethod, Response responseBody) {
RestTemplate restTemplate = new RestTemplate();
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(requestBody.getBody(),
this.securityHeaders);
ResponseEntity<? extends Response> response = restTemplate.exchange(url, httpMethod, request,
responseBody.getClass());
return response.getBody();
}
Currently my ResponseEntityExceptionHandler is the following
@ControllerAdvice
public class RestResponseExceptionHandler extends ResponseEntityExceptionHandler {
private static Logger log = LoggerFactory.getLogger(RestResponseExceptionHandler.class);
private HttpHeaders headers = new HttpHeaders();
@ExceptionHandler(value = { HttpClientErrorException.class, HttpServerErrorException.class })
protected ResponseEntity<Object> handleConflict(HttpStatusCodeException ex, WebRequest request) {
ErrorMessage responseBody = new ErrorMessage();
try {
JSONObject bodyOfException = new JSONObject(ex.getResponseBodyAsString());
log.warn("{}| {}", ex.getStatusCode(), bodyOfException);
responseBody.setErrorAndDescription(bodyOfException.optString("error"),
bodyOfException.optString("error_description"));
} catch (JSONException e) {
log.error("{}| Bad authentication response body | Response Body | {}", ex.getStatusCode(),
ex.getResponseBodyAsString());
}
return handleExceptionInternal(ex, responseBody, headers, ex.getStatusCode(), request);
}
}
However, only for HttpStatus 401 exceptions, I get an empty Response Body.
Example of logs:
400| {"error_description":"Bad client credentials","error":"invalid_client"}
401| Bad authentication response body | Response Body |
Does anyone know how I can obtain the response body for 401 exceptions?
Edit: When using a Postman to call the Authentication Server I get non null 401 responseBody:
{
"error": "invalid_token",
"error_description": "Token was not recognised"
}