Where to throw customized 404 error in jersey when

2019-06-17 18:37发布

问题:

I want to customize 404 response, that the server (not me) throws whenever it can't find a requested resource, (or throw a customized WebApplicationException myself, if it's possible to test if a requested resource is present in one app? probably a List of resources is stored somewhere?). please don't refer me to solutions that suggest to extend WebApplicationException, because even doing so, my problem is when to throw it?, when resource is not found! but how to express this need in jersey framework

回答1:

Jersey throws javax.ws.rs.NotFoundException when it cannot find an endpoint. Just use an exception mapper to transform it to a response of your choice:

import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {

    public Response toResponse(NotFoundException exception) {
        return Response.status(Response.Status.NOT_FOUND)
                .entity("No such resource")
                .build();
    }
}