2
votes

I have a Jersey REST API that returns 204 No content instead of 404 when the entity to be returned back is null.

To address this issue, I'm currently planning to throw an exception within the resource method so that it could force Jersey to return 404 like below.

if (feature == null) throw new WebApplicationException(404);

But I have various REST URIs that suffer from the same problem. Is there a way to address all of them without touching each and every resource method?

My resource methods look like this:

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.webapi.domain.Feature;
import com.example.webapi.service.FeatureService;

@Component
@Path("features")
@Produces(MediaType.APPLICATION_JSON)
public class FeatureResource {

    @Autowired
    private FeatureService featureService;

    @GET
    public List<Feature> getFeatures() {
        return featureService.listAllFeatures();
    }

    @GET
    @Path("{featureCode}")
    public Feature getFeature(@PathParam("featureCode") Integer featuresCode) {
        return featureService.findFeatureByFeatureCode(featuresCode);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response addFeature(Feature feature, @Context UriInfo uriInfo) {
        Integer id = (Integer) featureService.createFeature(feature);
        return Response.created(uriInfo.getAbsolutePathBuilder().path(id.toString()).build()).entity(feature).build();
    }
} 
2
You can send your own response code through the Response object.markbernard

2 Answers

1
votes

you can implement ContainerResponseFilter and customise the response based on your requirement.

ex:

@Provider
public class LoggingResponseFilter
    implements ContainerResponseFilter {

private static final Logger logger =      LoggerFactory.getLogger(LoggingResponseFilter.class);

public void filter(ContainerRequestContext requestContext,
        ContainerResponseContext responseContext) throws IOException {
    String method = requestContext.getMethod();

    logger.debug("Requesting " + method + " for path " + requestContext.getUriInfo().getPath());
    Object entity = responseContext.getEntity();
    if (entity != null) {
        logger.debug("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
    }
}

}

Customize the above code and implement your business logic.

1
votes

You can use Request or Response filters depends on what you want to check for null.

check the docs here