如何在Jersey客户端中引发自定义异常?

时间:2018-05-30 08:00:11

标签: java jax-rs jersey-2.0 jersey-client

我通过我的项目" shop" 学习Jersey和JAX-RS 2.x.每当HTTP响应为4xx或5xx时,我希望我的客户端SDK引发ShopException。以下是我在客户端构建器中注册ClientResponseFilter的尝试:

target =
    ClientBuilder.newBuilder()
        .register(ShopApplication.newJacksonJsonProvider())
        .register((ClientResponseFilter) (requestCtx, responseCtx) -> {
          if (responseCtx instanceof ClientResponse) {
            ClientResponse resp = (ClientResponse) responseCtx;
            if (resp.getStatus() >= 400) {
              ShopExceptionData data = resp.readEntity(ShopExceptionData.class);
              throw new ShopException(resp.getStatus(), data);
            }
          }
        })
        .build()
        .target(Main.BASE_URI.resolve("products"));

测试看起来像:

@Test
public void getProduct_invalidId() {
  try {
    target.path("123!").request(APPLICATION_JSON).get(Product.class);
    fail("GET should raise an exception");
  } catch (ShopException e) {
    assertThat(e.getData().getErrorCode()).isEqualTo(ShopError.PRODUCT_ID_INVALID.code);
    assertThat(e.getData().getErrorMessage()).isEqualTo(ShopError.PRODUCT_ID_INVALID.message);
  }
}

问题是,我的自定义ShopException被泽西抓住并包含在javax.ws.rs.ProcessingException中:

javax.ws.rs.ProcessingException
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:287)
    at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
    at io.mincong.shop.rest.ProductResourceIT.getProduct_invalidId(ProductResourceIT.java:64)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: io.mincong.shop.rest.ShopException
    at io.mincong.shop.rest.ProductResourceIT.lambda$setUp$0(ProductResourceIT.java:42)
    at org.glassfish.jersey.client.ClientFilteringStages$ResponseFilterStage.apply(ClientFilteringStages.java:133)
    at org.glassfish.jersey.client.ClientFilteringStages$ResponseFilterStage.apply(ClientFilteringStages.java:121)
    at org.glassfish.jersey.process.internal.Stages.process(Stages.java:171)
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:283)
    ... 33 more

是否有避免ProcessingException的解决方法,并确保抛出的异常为ShopException

1 个答案:

答案 0 :(得分:1)

注意:这是一个部分答案,因为我还没有解决所有情况。

如果查看JerseyInvocation的源代码,您将看到方法invoke(Class responseType),这是我们在请求传递我们希望响应反序列化的class参数时调用的方法至。这是你在这里使用的,传递Product.class

target.path("123!").request(APPLICATION_JSON).get(Product.class);

查看invoke()方法的来源,我们可以看到

return requestScope.runInScope(new Producer<T>() {
    @Override
    public T call() throws ProcessingException {
        try {
            return translate(runtime.invoke(requestForCall(requestContext)), requestScope, responseType);
        } catch (final ProcessingException ex) {
            if (ex.getCause() instanceof WebApplicationException) {
                throw (WebApplicationException) ex.getCause();
            }
            throw ex;
        }
    }
});

translate方法包含ProcessingException中的异常。如果你看看catch之后的几行,你应该看到我们有机会找到解决方法。如果异常的原因是WebApplicationException,那么将抛出该异常。因此,您的解决方法是ShopException扩展WebApplicationException

现在我说这只是一个部分答案,因为当你只想从请求中找回Response时这不起作用

Response res = target.path("123!").request(APPLICATION_JSON).get();

执行此操作时,将调用invoke() (no arguments)。它与先前的invoke()方法没有做同样的事情。所以,如果你能解决这个问题,那么你就有了完整的解决方案。

另一种解决方法是自己抓住ProcessingException并重新抛出原因。如果您正在制作SDK,那么无论如何都会完全不知道这一点。