在 Jersey REST 客户端中模拟错误代码
我正在编写一个 REST 服务以及一个 REST 客户端来调用该服务。
我们有一堆错误代码,有些可以重试,有些则不能。我想编写一个客户端,如果可能的话会重试,否则会显示这些错误。我现在的主要问题是我不知道如何模拟我想要处理的响应。
例如,我正在做:
Client client = Client.create();
WebResource resource = client.resource("http://localhost:<port>/test");
resource.type(MediaType.APPLICATION_JSON);
ClientResponse response = resource.get(ClientResponse.class);
if (response.getClientResponseStatus().getStatusCode() == 404) {
//do something
}
有没有一种好的方法可以覆盖特定的类或在其上设置处理程序,以便我可以模拟我想要测试和处理的所有错误代码?
I am writing a REST service and also a REST client to call said service.
We have a bunch of error codes, some are retry-able, some are not. I want to write a client that retries if possible and otherwise surfaces these errors. My main issue right now is that I don't know how to simulate the responses I want to handle.
For example I'm doing:
Client client = Client.create();
WebResource resource = client.resource("http://localhost:<port>/test");
resource.type(MediaType.APPLICATION_JSON);
ClientResponse response = resource.get(ClientResponse.class);
if (response.getClientResponseStatus().getStatusCode() == 404) {
//do something
}
Is there a good way to overwrite a particular class or set a handler on this so that I can simulate all of the error codes I want to test and handle?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我得出的答案:
我之前不知道如何设置响应的状态,但可以通过 HTTPServletResponse 本地字段来实现。
然后,根据 REST 调用中的某些属性,您可以通过 dong response.setStatus(440) 或其他方式返回特定响应。
不要忘记在您的响应上添加 @Context 注释,以便 jersey magic 可以实例化它。
@语境
HTTPServletResponse 响应;
Here is the answer I've come up with:
I did not know how to set status on a response, earlier, but it can be achieved with an HTTPServletResponse local field.
Then based on some property in your REST call you can return a specific response by dong response.setStatus(440) or whatever.
Don't forget to put a @Context annotation on your response so that jersey magic can instantiate it.
@Context
HTTPServletResponse response;