我正在开发一个项目,在该项目中我正在对我的服务器进行休息 url 调用,这会返回一个 JSON 字符串作为响应。如果服务有任何问题,那么它会给我以下 JSON 字符串中的任何一个作为错误响应 -
{"error":"no user_id passed"}
or
{"warning": "user_id not found", "user_id": some_user_id}
or
{"error": "user_id for wrong partition", "user_id": some_user_id, "partition": some_partition}
or
{"error":"no client_id passed"}
or
{"error": "missing client id", "client_id":2000}
但如果它是成功响应,那么我将返回 json 字符串作为 -
{"@data": {"oo":"1205000384","p":"2047935"}
下面是我进行调用的代码,response
如果服务端出现问题或成功,这里的变量将具有 JSON 字符串以上的内容。
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
// here response has the JSON string
ClientResponse clientResponse = checkJSONResponse(response);
return clientResponse;
目前我正在返回响应,而不检查任何内容。但是现在我正在考虑验证响应并查看它是否是错误,然后将其记录为特定错误,如果它是成功响应,则返回它。
第一个选项:-那么我response
每次调用都应该反序列化上面的json字符串,然后看看它是否有成功或错误响应。
第二个选项:-或者我应该只检查响应字符串是否以错误或警告开头,如果它以错误或警告开头,然后反序列化响应并提取特定的错误消息。
因为在大多数情况下,我们将获得返回数据的成功响应,并且只有大约 2% 我们将获得高于错误响应的返回,所以我认为每次反序列化仅提取错误情况与startsWith
错误或警告相比会很昂贵选项然后反序列化它?
第一个选项-
private ClientResponse checkJSONResponse(final String response) throws Exception {
Gson gson = new Gson();
ClientResponse clientResponse = null;
JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse
if (jsonObject.has("error") || jsonObject.has("warning")) {
final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
.get("warning").getAsString();
// log error here
ClientResponse clientResponse = new ClientResponse(response, "ERROR_OCCURED", "SUCCESS");
} else {
ClientResponse clientResponse = new ClientResponse(response, "NONE", "SUCCESS");
}
return clientResponse;
}
第二种选择-
private ClientResponse checkJSONResponse(final String response) throws Exception {
Gson gson = new Gson();
ClientResponse clientResponse = null;
if(response.startsWith("{\"error\":") || response.startsWith("{\"warning\":")) {
JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse
if (jsonObject.has("error") || jsonObject.has("warning")) {
final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
.get("warning").getAsString();
// log error here with specific messages
ClientResponse clientResponse = new ClientResponse(response, "ERROR_OCCURED", "SUCCESS");
}
} else {
ClientResponse clientResponse = new ClientResponse(response, "NONE", "SUCCESS");
}
return clientResponse;
}
对于我的用例,这里的最佳选择是什么?我主要是从性能角度看哪个选项会更有效?