1
votes

I am creating a REST service using jersey 2.0. I am extending WebApplicationException

Method raising a particular exception

if(json.equals("") || json.equals(" ")) {
      throw new ArgumentException("bad post data");
}


      public class ArgumentException extends RestException  {
         .....

         public ArgumentException(String message) {
             super(Status.BAD_REQUEST,message);
         }
    }


    public class RestException extends WebApplicationException  {
    ...........
     public RestException(Status status, String message) {

             super(Response.status(status)
                     .entity(message)
                     .type("text/plain")
                     .build()); 
             /*
             super(Response.status(status)
                     .entity(new ErrorBean(status.getStatusCode(),message))
                     .type(MediaType.APPLICATION_JSON)
                     .build()); */

         }


ErrorBean is a POJO

The method that returns error as plain string inside RestException works (right http code 400 and message). However when I try to pass the ErrorBean POJO and use MediaType.APPLICATION_JSON in response I get an error saying "Headers have already been sent" with http error code 500 (so some internal problem with plumbing) and empty response.

I have also looked at this question Returning JSON or XML for Exceptions in Jersey

How can I return the exception with code and message as a JSON like

{"code" : 400, "message" : .... }

Update

I have received answer on SO as well as jersey users mailing list. steps are

  • A non AJXB POJO does not need any annotations
  • Register JacksonFeature in your application

ResourceConfig rc = new ResourceConfig().packages("test").register(JacksonFeature.class);

1

1 Answers

2
votes

You need to register JacksonFeature in your Application/ResourceConfig, i.e.:

// Create JAX-RS application.
final Application application = new ResourceConfig()
        .packages("org.glassfish.jersey.examples.jackson")
        .register(JacksonFeature.class)
        // No need to register this provider if no special configuration is required.
        .register(MyObjectMapperProvider.class);

Take a look at the documentation for Jackson support in Jersey and also at the example.