I use Jersey API for my REST service. My question is: Is there a more elegant way of returning exceptions in a JSON form? Is it better to concern myself with creating a json obj
You can wrap your error into a class, say I have an ErrorData class which has status, message and stacktrace. Everytime an exception occurs, I throw a GeneralAppException with the errordata object.
public class GeneralAppException extends WebApplicationException {
public GeneralAppException(ErrorData er) {
super(Response.status(er.getStatusCode()).
entity(er).type(MediaType.APPLICATION_JSON).build());
}
}
I have another class which has all the known errors, eg.
public static final ErrorData NODATAFOUND = new ErrorData(Response.Status.NOT_FOUND.getStatusCode(),"No data was found for given query");
public static final ErrorData CODEERROR = new ErrorData(502,"CodeError");
Your catch can look like
catch (ExceptionREST e) {
throw new GeneralAppException(ErrorData.NODATAFOUND);
}
Reference used : https://jersey.java.net/documentation/latest/representations.html#d0e6665