简体   繁体   English

如何使用正则表达式识别JSON字符串中的错误消息?

[英]How to use regular expressions to identify the error message in the JSON String?

I am working on a project in which I am making a call to one of my servers using RestTemplate which is running a restful service and getting the response back from them. 我正在一个项目中,在该项目中,我正在使用RestTemplate调用我的一台服务器,该服务器正在运行一个宁静的服务并从中获取响应。

The response that I will be getting from my server can be either of these error responses (that's all I have for error response) if something has gone wrong - 如果出了问题,我将从服务器获得的响应可以是这些错误响应中的任何一个(这就是我对错误响应的全部响应)-

{"warning": "user_id not found", "user_id": some_user_id}
{"error": "user_id for wrong partition", "user_id": some_user_id, "partition": some_partition}
{"error": "missing client id", "client_id":2000}

or below successful response (it can be any random json string key can also be different) - 或低于成功的响应(可以是任何随机json字符串键,也可以不同)-

{"@data": {"oo":"1205000384","p":"2047935"} 
  1. If I am getting any error response as mentioned above, then I am deserializing it (my bad :( ) so that I can log them as an error with a specific error or warning I got front the server which can be for example - user_id not found or missing client id . 如果我收到如上所述的任何错误响应,则我将其反序列化(我很糟糕:(),以便可以将它们记录为具有特定errorwarning ,例如我到达服务器的前面,例如user_id not foundmissing client id
  2. If it is a successful response then also I am deserializing it which I don't need for my use case as we don't have any POJO and I just need to return the response as it is which I have got from the server. 如果它是一个成功的响应,那么我也将反序列化它,因为我们没有任何POJO,所以我不需要用例,我只需要返回从服务器获得的响应即可。

In my use case, I don't need to deserialize my response string if it is a successful response as we don't have any POJO for that and we are returning the response string as it is which we have got from the server. 在我的用例中,如果它是成功的响应,则不需要反序列化我的响应字符串,因为我们对此没有任何POJO,并且将返回从服务器获得的响应字符串。 But just for logging specific error messages (if I am getting error response from the server) I am deserializing it which I am thinking is unnecessary. 但是只是为了记录特定的错误消息(如果我从服务器获取错误响应),我正在反序列化它,我认为这是不必要的。 There might be better solution for my use case. 对于我的用例,可能会有更好的解决方案。

Below is my Java client which is calling Callable task using future.get - 下面是我的Java客户端,它使用future.get调用Callable任务-

public class TestingClient implements IClient {

    private ExecutorService service = Executors.newFixedThreadPool(10);
    private RestTemplate restTemplate = new RestTemplate();

    @Override
    public String executeSync(ClientKey keys) {

        String response = null;
        try {

            ClientTask ClientTask = new ClientTask(keys, restTemplate);
            Future<String> future = service.submit(ClientTask);
            response = handle.get(keys.getTimeout(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {

        } catch (Exception e) {

        }

        return response;
    }
}

And now below is my ClientTask class which implements Callable interface. 现在下面是我的ClientTask类,该类实现Callable接口。 In the call method, I am generating an URL and then hit the server using RestTemplate and get the response back - 在call方法中,我生成一个URL,然后使用RestTemplate命中服务器并返回响应-

class ClientTask implements Callable<String> {

    private ClientKey cKeys;
    private RestTemplate restTemplate;

    public ClientTask(ClientKey cKeys, RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.cKeys = cKeys;
    }

    @Override
    public String call() throws Exception {

        // .. some code here
        String url = "some_url";            
        String response = restTemplate.getForObject(url, String.class);

        String test = checkJSONResponse(response);

        return test;
    }

    private String checkJSONResponse(final String response) throws Exception {

        // may be there are some better way of doing it for my scenario instead of using GSON
        Gson gson = new Gson();
        String str = null;
        JsonObject jsonObject = gson.fromJson(response, JsonObject.class); // parse it, may be performance issues here/
        if (jsonObject.has("error") || jsonObject.has("warning")) {

        final String error = jsonObject.get("error") != null ? jsonObject.get("error").getAsString() : jsonObject
        .get("warning").getAsString();

        // log specific `error` here using log4j
        str = response;
        } else {
            str = response;
        }

        return str;
    }
}

As you can see in my above code we are deserializing the JSON string only to log specific error messages if we are getting any error response back. 如您在上面的代码中看到的,如果我们得到任何错误响应,我们将反序列化JSON字符串仅记录特定的错误消息。 But for successful response we don't need any deserialization but still we are doing it. 但是对于成功的响应,我们不需要任何反序列化,但是我们仍在这样做。

Is there any better way of solving this problem? 有解决这个问题的更好方法吗? Because currently I am seeing some performance issues with the GSON deserialization. 因为当前我看到GSON反序列化的一些性能问题。

The only way I can identify successful response along with error response is with error or warning in the response so I am thinking of using regular expressions which can identify error or warning as the key in the response string. 我可以识别成功响应和错误响应的唯一方法是响应中包含errorwarning ,因此我考虑使用正则表达式将错误或警告标识为响应字符串中的键。 If they contain error or warning in the response string then extract the specific error or warning message and log it. 如果它们在响应字符串中包含错误或警告,则提取特定的错误或警告消息并记录下来。

I guess there might be some better way of solving this problem without paying the cost for deserialization. 我想可能有一些更好的方法可以解决此问题,而不必付出反序列化的费用。

Just relying on a regex is I think to dangerous. 我认为仅仅依靠正则表达式是很危险的。 What if the server slightly changes the output format? 如果服务器稍微更改输出格式怎么办?

I would try to make a quick test, possibly with a simple regexp looking for the string "error" and if there is a chance that it is an error response do a full deserialization to determine if it really was an error or not. 我将尝试进行快速测试,可能使用简单的正则表达式来查找字符串"error"并且如果有可能是错误响应,请进行完全反序列化以确定是否确实是错误。

You would pay the extra cost only for false positives when a regular response by chance triggers the quick check. 当常规响应偶然触发快速检查时,您只需为误报支付额外费用。

我将使用http代码来控制成功/失败数据解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM