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?
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.
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.
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
}
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