[英]Jersey ExceptionMapper, rely on another ExceptionMapper
我有一個ExceptionMapper
,它是通用公共庫的一部分:
@Provider
public class GenericExceptionMapper implements ExceptionMapper<GenericException> {
...
}
現在,在我的特定項目中,我有自己的ExceptionMapper
:
@Provider
public class SomeAdHocExceptionMapper implements ExceptionMapper<SomeAdHocException> {
...
}
我想將SomeAdHocException
轉換為GenericException
並讓GenericExceptionMapper
負責進一步處理。 我嘗試了以下兩個選項,但兩個都不起作用:
[1]在SomeAdHocExceptionMapper
拋出GenericException
:
@Provider
public class SomeAdHocExceptionMapper implements ExceptionMapper<SomeAdHocException> {
public Response toResponse(SomeAdHocException e) {
throw new GenericException(e);
}
}
[2]將GenericExceptionMapper
注入SomeAdHocExceptionMapper
:
@Provider
public class SomeAdHocExceptionMapper implements ExceptionMapper<SomeAdHocException> {
@Inject
private GenericExceptionMapper mapper;
public Response toResponse(SomeAdHocException e) {
return mapper.toResponse(new GenericException(e));
}
}
這兩個選項都給予依賴性刪除。
我該如何解決這個問題?
您的第一次嘗試將無法工作,因為只能為單個請求調用一個異常映射器。 這是一個安全功能,可確保我們不會遇到無限循環。 試想XExceptionMapper
拋出一個YException
處理時以及YExceptionMapper
拋出一個XException
處理過程中。
您的第二次嘗試將無法工作,因為映射器不可注入。 你可以實例化它。
@Provider
public class SomeAdHocExceptionMapper implements ExceptionMapper<SomeAdHocException> {
private final GenericExceptionMapper mapper = new GenericExceptionMapper();
public Response toResponse(SomeAdHocException e) {
return mapper.toResponse(new GenericException(e));
}
}
假設存在這樣的構造函數,並且通用映射器不需要對它自己進行任何注入。 如果是,您可以使映射器可注入。
public class AppConfig extends ResourceConfig {
public AppConfig() {
register(new AbstractBinder() {
@Override
protected void configure() {
bindAsContract(GenericExceptionMapper.class);
}
});
}
}
然后你就可以注射了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.