I am new to this, trying to achieve reading some docs but its not working, please bear with me.
I have created a UserNotFoundMapper
using ExceptionMappers
like this:
public class UserNotFoundMapper implements ExceptionMapper<UserNotFoundException> {
@Override
public Response toResponse(UserNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
}
}
This in my service:
@GET
@Path("/user")
public Response getUser(@QueryParam("id") String id) throws UserNotFoundException{
//Some user validation code with DB hit, if not found then
throw new UserNotFoundException();
}
The UserNotFoundException
is an User-Defined
Exception.
I tried this:
public class UserNotFoundException extends Exception {
//SOME block of code
}
But when I invoke the service, the UserDefinedExceptionMapper
is not getting invoked. It seems I might be missing something in the UserDefinedException
. How to define this exception then?
Please let me know how to define the UserNotFoundException
.
You need to annotate your exception mapper with @Provider
, otherwise it will never get registered with the JAX-RS runtime.
@Provider
public class UserNotFoundMapper implements
ExceptionMapper<UserNotFoundException> {
@Override
public Response toResponse(UserNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain")
.build();
}
}