Returning JSON or XML for Exceptions in Jersey

Posted by Dominic on Stack Overflow See other posts from Stack Overflow or by Dominic
Published on 2010-05-20T08:01:20Z Indexed on 2010/05/20 8:10 UTC
Read the original article Hit count: 190

Filed under:
|
|
|
|

My goal is to have an error bean returned on a 404 with a descriptive message when a object is not found, and return the same MIME type that was requested.

I have a look up resource, which will return the specified object in XML or JSON based on the URI (I have setup the com.sun.jersey.config.property.resourceConfigClass servlet parameter so I dont need the Accept header. My JAXBContextResolver has the ErrorBean.class in its list of types, and the correct JAXBContext is returned for this class because I can see in the logs).

eg: http://foobar.com/rest/locations/1.json

@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Location getCustomer(@PathParam("id") int cId) {
   //look up location from datastore
    ....
    if (location == null) {
        throw new NotFoundException("Location" + cId + " is not found");
     }

}

And my NotFoundException looks like this:

public class NotFoundException extends WebApplicationException {

    public NotFoundException(String message) {
        super(Response.status(Response.Status.NOT_FOUND).
                entity(new 
                        ErrorBean(
                           message, 
                           Response.Status.NOT_FOUND.getStatusCode()
                        )
                .build());
    }

}

The ErrorBean is as follows:

@XmlRootElement(name = "error")
public class ErrorBean {

    private String errorMsg;
    private int errorCode;

        //no-arg constructor, property constructor, getter and setters
        ...

}

However, I'm always getting a 204 No Content response when I try this. I have hacked around, and if I return a string and specify the mime type this works fine:

public NotFoundException(String message) {
    super(Response.status(Response.Status.NOT_FOUND).
            entity(message).type("text/plain").build());
}

I have also tried returning an ErrorBean as a resource. This works fine:

{"errorCode":404,"errorMsg":"Location 1 is not found!"}

© Stack Overflow or respective owner

Related posts about jersey

Related posts about JSON