【发布时间】:2016-10-20 13:09:59
【问题描述】:
我需要编写一个返回特定对象的多个应用程序使用的 RestClient。 如果出现错误请求(400),我想建议调用者应用消息错误和状态代码。 我想知道使用 code 和 message 属性抛出托管异常是否是一种好的行为,以便从调用者代码中正确捕获。 像这样的:
RestClient.java
ClientResponse response;
try {
response = client.resource(requestURI).queryParams(queryParams)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, richiesta);
boolean output = response.getStatus() == Response.Status.NO_CONTENT.getStatusCode();
if (!output && response.getStatus() == Response.Status.BAD_REQUEST)
throw new RestClientRuntimeException(response.getStatus, response.getEntity(String.class));
} catch (ClientHandlerException e) {
throw new RestClientRuntimeException(e);
} catch (UniformInterfaceException e) {
throw new RestClientRuntimeException(e);
}
来电应用
try
{
boolean output = restClient.method()
} catch (RestClientRuntimeException e) {
// read exception status and message entity
}
这是一个好习惯吗?
【问题讨论】:
-
我认为你搞错了:客户端永远不会从你的服务器代码中看到任何 Java 异常。要使客户端可以使用它,您必须将其添加到 HTTP 响应中或将其放入 HTTP 响应代码 (400)。
-
为什么不呢? if (!output && response.getStatus() == Response.Status.BAD_REQUEST) throw new RestClientRuntimeException(response.getStatus, response.getEntity(String.class));