Skip to content

Commit

Permalink
ResponseStatusExceptionFilter: Fix unwrap of JSON message
Browse files Browse the repository at this point in the history
Reading the entity stream a second time without resetting it was causing
the ObjectMapper to return null then a NullPointerExceptions when
calling get('message') method on it.

Fix the issue by creating the ObjectMapper from the String
representation of the entity stream instead of resetting the stream to
read it a second time. Also check to make sure the returned JsonNode is
not null and that the content is text.

Closes #1222
  • Loading branch information
hugares committed Jul 16, 2019
1 parent 5c3ba9a commit 2010582
Showing 1 changed file with 15 additions and 5 deletions.
Expand Up @@ -10,6 +10,8 @@
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -31,6 +33,8 @@
*/
public class ResponseStatusExceptionFilter implements ClientResponseFilter {

private static final Logger LOG = LoggerFactory.getLogger(ResponseStatusExceptionFilter.class);

@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
int status = responseContext.getStatus();
Expand Down Expand Up @@ -79,13 +83,19 @@ private String getBodyAsMessage(ClientResponseContext responseContext) {
String message = IOUtils.toString(entityStream, charset);

if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(entityStream).get("message");
if (node != null) {
message = node.textValue();
try {
JsonNode node = new ObjectMapper().readTree(message);
if (node != null) {
JsonNode messageNode = node.get("message");
if (messageNode != null && messageNode.isTextual()) {
message = messageNode.textValue();
}
}
} catch (IOException e) {
// ignore parsing errors and return the message as is
LOG.debug("Failed to unwrap error message: {}", e.getMessage(), e);
}
}

return message;
} catch (Exception ignored) { }
}
Expand Down

0 comments on commit 2010582

Please sign in to comment.