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
.
Thrown exceptions are handled by the JAX-RS runtime if you have registered an exception mapper. Exception mappers can convert an exception to an HTTP response. If the thrown exception is not handled by a mapper, it is propagated and handled by the container (i.e., servlet) JAX-RS is running within.
ExceptionMapper is a contract for a provider that maps Java exceptions to Response object. An implementation of ExceptionMapper interface must be annotated with @Provider to work correctly.
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With