I have a Jersey REST service and would like to have a GET method that returns void on success but returns an ErrorResponse object if there's an issue. Here's what my method looks like:
@GET
@Path(ResourceConstants.PATH_START_BATCH)
@Produces(MediaType.APPLICATION_JSON)
public void startBatch(@QueryParam(ResourceConstants.PARAM_BATCH_ID) String batchId)
{
try
{
batchService.startBatch(batchId);
}
catch (Exception ex)
{
ErrorResponse errorResponse = new ErrorResponse();
Map<String, String> responseDetails = errorResponse.getResponseDetails();
responseDetails.put("Failure", "Failed to start with exception " + ex.getMessage());
throw WebServiceException.generate(ex, errorResponse);
}
}
and the WebServiceException class looks like this:
public class WebServiceException extends WebApplicationException
{
private static final long serialVersionUID = 1L;
public WebServiceException(ErrorResponse errorResponse)
{
super(Response.serverError()
.status(Status.INTERNAL_SERVER_ERROR)
.entity(errorResponse)
.type(MediaType.APPLICATION_JSON)
.build());
}
public WebServiceException(Throwable throwable, Response response)
{
super(throwable, response);
}
public static WebServiceException generate(Throwable throwable, ErrorResponse errorResponse)
{
Throwable rootCause = WebServiceException.getRootCause(throwable);
Response response = Response.serverError()
.status(Status.INTERNAL_SERVER_ERROR)
.entity(errorResponse)
.type(MediaType.APPLICATION_JSON)
.build();
return new WebServiceException(rootCause, response);
}
private static Throwable getRootCause(Throwable current)
{
Throwable root = current.getCause();
if (root != null)
{
return WebServiceException.getRootCause(root);
}
else
{
return current;
}
}
}
When I test with an invalid batch ID, my response back is empty a set of empty braces {}.
Can I return a JSON object in the error if the method returns void?