如何在 Jersey Client 中引发自定义异常?
How to raise customized exception in Jersey Client?
我正在通过我的项目 "shop" 学习 Jersey 和 JAX-RS 2.x。我希望我的客户端 SDK 在 HTTP 响应为 4xx 或 5xx 时引发 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
被 Jersey 捕获并包裹成 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(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.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.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=12=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.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[=12=](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
?
注意:这是部分答案,因为我还没有弄清楚所有情况。
如果您查看 JerseyInvocation
, you will see the method 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,那么这一切都将在用户不知情的情况下完成。
我正在通过我的项目 "shop" 学习 Jersey 和 JAX-RS 2.x。我希望我的客户端 SDK 在 HTTP 响应为 4xx 或 5xx 时引发 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
被 Jersey 捕获并包裹成 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(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.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.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=12=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.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[=12=](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
?
注意:这是部分答案,因为我还没有弄清楚所有情况。
如果您查看 JerseyInvocation
, you will see the method 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,那么这一切都将在用户不知情的情况下完成。