Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URI-specific ExceptionMapper in JAX-RS

I'm using Jersey, and Guice as my IOC-container. I'd like to know if it is possible to associate an ExceptionMapper with a specific URI. The reason for this is that I want to map the same exception differently based on what URI was visited. For example, suppose I've got the following two exception mappers for my custom exception:

public class MyExceptionMapperForFirstURI implements
  ExceptionMapper<MyException> {..return response based on first URI..}

public class MyExceptionMapperForSecondURI implements
  ExceptionMapper<MyException> {..return response based on second URI..}

As far as I understand you bind an ExceptionMapper in your ServletModule as follows:

public class MyModule extends ServletModule {

    @Override
    public void configureServlets() {
        super.configureServlets();
        bind(MyCustomExceptionMapper.class);
    }
}

How would I go about binding MyExceptionMapperForFirstURI and MyExceptionMapperForSecondURI so that they get associated with the correct URIs. Is this possible, and if possible: is this the correct way to do this?

like image 298
wcmatthysen Avatar asked Sep 28 '11 09:09

wcmatthysen


People also ask

How to handle exception 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 an exception Mapper?

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.

How do you handle exceptions in Jersey?

Approach 2 : Annotating a class with @ControllerAdvice and define methods with @ExceptionHandler. This is similar to Controller based exception (refer approach 1) but this is used when controller class is not handling the exception. This approach is good for global handling of exceptions in Rest Api.


1 Answers

This is quite late answer ;-) but you can always inject the UriInfo and branch on that. So,

@Context
UriInfo uriInfo;

.....

if (matchesA(uriInfo.getAbsolutePath())) {
    // do something
}
like image 140
shabyasachi Avatar answered Sep 28 '22 04:09

shabyasachi