URI-specific ExceptionMapper in JAX-RS

試著忘記壹切 提交于 2019-12-22 06:55:34

问题


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?


回答1:


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
}



回答2:


Not sure how the URI's of your app look like, but if it is possible to split your app into two servlets or filters, then you can do it like that - i.e. have one servlet/filter serve one set of resources and include the first mapper and have the other servlet/filter serve the other set of resources and include the other mapper.

If these are custom exceptions, you can also pass Request as an argument to the exception and have just a single mapper - decide on the response based in the request uri in the mapper.



来源:https://stackoverflow.com/questions/7581393/uri-specific-exceptionmapper-in-jax-rs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!