Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to throw customized 404 error in jersey when HttpServer can't find a resource

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

like image 335
Curcuma_ Avatar asked Oct 30 '14 18:10

Curcuma_


1 Answers

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();
    }
}
like image 66
Lukasz Wiktor Avatar answered Oct 21 '22 05:10

Lukasz Wiktor