users@jersey.java.net

[Jersey] jersey 2.0 jaxrs RI - return json string on exception

From: rajeev jha <rjha94_at_gmail.com>
Date: Sat, 20 Jul 2013 13:10:10 +0530

Hi

I have posted this on SO as well (
http://stackoverflow.com/questions/17747681/jersey-2-0-jaxrs-ri-return-json-string-on-exception
)


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

1)
**Method raising a particular exception**

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

       2)
          public class ArgumentException extends RestException {
             .....

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

3)
        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()); */

             }

           4)

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
http://stackoverflow.com/questions/2871935/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" : .... }


Thanks

/rajeev