Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAX-RS jersey ExceptionMappers User-Defined Exception

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.

like image 834
WhoAmI Avatar asked Mar 03 '13 11:03

WhoAmI


People also ask

How do you handle exceptions in JAX RS?

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.

What is exception mapper in Java?

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.


1 Answers

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();     } } 
like image 69
Perception Avatar answered Oct 05 '22 22:10

Perception