簡體   English   中英

Jersey - 為資源方法注冊ExceptionMapper

[英]Jersey - Register ExceptionMapper for Resource Methods

特定類的異常處理/映射問題讓我想到了如何將ExceptionMapper注冊到特定的資源方法

我試過使用像這樣的DynamicFeature

DynamicFeature

@Provider
public class ExceptionMapperDynamicFeature implements DynamicFeature {

    @Override
    public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
        if(!resourceInfo.getResourceMethod().isAnnotationPresent(BindExceptionMapper.class))
            return;
        BindExceptionMapper bem = resourceInfo.getResourceMethod().getAnnotation(BindExceptionMapper.class);
        context.register(bem.mapper());
    }

}

注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BindExceptionMapper {
    Class<? extends ExceptionMapper<?>> mapper() default WebApplicationExceptionMapper.class;
}

資源

@GET
@Produces(MediaType.APPLICATION_JSON)
@BindExceptionMapper 
public Response test() {
    // do something that throws an exception
}

結果是幻想破滅:

警告:類的給定契約(接口javax.ws.rs.ext.ExceptionMapper)... WebApplicationExceptionMapper提供程序不能綁定到資源方法。

然后我在沒有運氣的情況下尋找其他可能性,最后得到了一個AspectJ實現,你可以看到它作為對上述鏈接問題的答案一部分

那么完整的問題:

有沒有辦法成功將ExceptionMapper注冊到資源方法?

而且當然,

  • 如果是的話:怎么樣?
  • 如果沒有那么:為什么?

我很好奇答案:)

請注意:
這個問題不是要將ExceptionMapper注冊到資源類,如...

public class ApplicationResourceConfig extends ResourceConfig {
    public ApplicationResourceConfig() {
        register(WebApplicationExceptionMapper.class, TestResource.class);
    }
}

尤其不是要注冊它們。

這不完全是你問的問題,但這是我發現做你想要的事情的唯一方法:

@Provider
public class ErrorExceptionHandler implements ExceptionMapper<Throwable> {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public Response toResponse(final Throwable exception) {
        // this is an example of how to do something custom based on an annotation
        if(!resourceInfo.getResourceClass().isAnnotationPresent(SomeCustomAnnotation.class) && !resourceInfo.getResourceMethod().isAnnotationPresent(SomeCustomAnnotation.class))
            return null; // do some custom thing here based on your annotation, maybe call another ExceptionMapper not annotated with @Provider ?
        return Response.status(500).entity("ERROR").build();
    }
}

無論如何,它適用於我的目的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM