2

I am working on a REST application built with Jackson-2.2.3.

Here is the Dependency:

<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.2.3</version>
</dependency>

I have a simple endpoint to create a User as below:

@POST
@Path(value = "/addUser")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(User user) {
    ...
}

As this endpoint consumes JSON, when api users send JSON Jackson will desearilize to User object.

If user invoke the endpoint with faulty JSON like, missing a property or bad structure. I want to log the fault JSON as a string and ERROR. How can I achieve that?

I tried using Filters but didn't work.

Kishor Prakash
  • 8,011
  • 12
  • 61
  • 92
  • Show the filter that failed to log – Ori Marko Sep 03 '19 at 11:51
  • @Kishor Prakash, why do you want this? If client sends a wrong json, he gets an error response. In the log on the server side, you get an error message from Jackson. Both should contain exact attributes, that are wrong. The createUser method will not be invoked in this case. What is the purpose to have something additionally? – Alexandr Sep 03 '19 at 13:32
  • @Alexandr I want to log the client specific ID from payload and visualize with graph in ELK. – Kishor Prakash Sep 03 '19 at 13:53

1 Answers1

0

Consider handling the JsonParseException:

Exception type for parsing problems, used when non-well-formed content (content that does not conform to JSON syntax as per specification) is encountered.

To achieve it, you could use an ExceptionMapper:

@Slf4j
@Provider
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {

    @Override
    public Response toResponse(JsonParseException exception) {
        log.error("Cannot parse JSON", exception);
        return Response.status(Response.Status.BAD_REQUEST)
                       .entity("Cannot parse JSON")
                       .type(MediaType.TEXT_PLAIN)
                       .build();
    }
}

For logging purposes, you may also be interested in getting some details from JsonLocation using exception.getLocation().


To register the exception mapper in Jersey, refer to this answer.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359