3

This is my first time writing code in Java I m running in to JsonParseException when I send invalid json data in my request body. I know I have to catch this error at the point where json body is getting parsed I don't have any idea how it works in my code. It would be great if someone can explain me how to catch the error and send the 400 response instead of the 500 which is being thrown as Uncaught server error and also how the request body is getting parsed. I m using JAXRS: 2.0.1 and jackson for Json parsing it seems. I also added an exceptionMapper to handle these exceptions but it doesn't seem to work.

//./src/main/java/com.test.rest/Routes.java
package.com.test.rest;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
public class Routes implements Xyz{

    @POST
    @Path("test")
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces(MediaType.APPLICATION_JSON)
    public Response testJson(@Context HttpHeaders headers, @HeaderParam("abc") String abc, TestRequest request){

         if(abc == null){
           return Response.status(Response.Status.BAD_REQUEST).entity("Invalid headers").build();
         }else{
           return Response.status(Response.Status.OK).entity(request.gettestData()).build();
         }
    }
}

./src/main/java/com.test.rest/TestRequest.java

package.com.test.rest;

public class TestRequest {
    private String testData;

    public TestRequest () {
    }
    public TestRequest(String testData){
        setTestData(testData);
    }

    public String gettestData(){
        return testData;
    }
    public void setTestData(String testData){
        if(testData!=null){
            testData = testData.toLowerCase();
        }
        this.testData =testData;
    }
}

./src/main/java/com.test.rest/JsonParseExceptionMapper.java

package.com.test.rest;

import com.fasterxml.jackson.core.JsonParseException;

import javax.annotation.Priority;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.core.*;

@Provider
@Priority(1)
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {
    @Override
    public Response toResponse(final JsonParseException exception) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Cannot parse JSON")
                .type(MediaType.TEXT_PLAIN)
                .build();
    }
}

All the files are in same level and I m using gradle to build my code
this is my request body

{
    "testData":
}
//com.fasterxml.jackson.core.JsonParseException: Unexpected character
saketh
  • 720
  • 1
  • 6
  • 18

0 Answers0