[英]What is the best way to handle GraphQl response in Java
In a legacy application with Java 6 I am calling a GraphQl API using Spring RestTemplate, now I would like to know what is the best way to handle the response, once GraphQl always will give a response with StatusCode 200 in case of success or error and the difference is that inside the body response there will be a string with "data" for success and "errors" for errors. 在使用Java 6的旧版应用程序中,我正在使用Spring RestTemplate调用GraphQl API,现在我想知道处理响应的最佳方法是什么,一旦GraphQl总是会在成功或错误的情况下给出StatusCode 200的响应,并且区别在于,在主体响应内部将有一个字符串,其中“成功”和“错误”代表错误。 I was thinking that I can get the response and convert to String and check using "contains" and check if there is "data" or "errors" inside the response body, but I do not know if it is the best way.
我以为我可以获取响应并将其转换为String并使用“包含”进行检查,并检查响应正文中是否存在“数据”或“错误”,但是我不知道这是否是最佳方法。 The code below is how the Java application is calling the GraphQl API:
以下代码是Java应用程序调用GraphQl API的方式:
ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
The way that I thought to handle is: 我认为要处理的方式是:
if (response.getBody().toString().contains("errors")){
handleException
}
GraphQL will give the response body in the following JSON
format GraphQL将以以下
JSON
格式提供响应正文
{
"data": { ... },
"errors": [ ... ]
}
If there were errors , it will have an errors fields. 如果有错误,它将有一个错误字段。
So , it is a bad idea as you are checking if the whole JSON response contains an errors
string rather than errors
field. 因此,这是一个坏主意,因为您要检查整个JSON响应是否包含
errors
字符串而不是errors
字段。 It will definitely fail for the success case just because data
contains a errors
string (eg Think about it is a get user request but an user use errors
as his login ID) 对于成功案例,肯定会失败,仅因为
data
包含errors
字符串(例如,考虑到这是一个获取用户请求,但是用户使用errors
作为其登录ID)
You should parse the response body into the JSON object and check if the JSON contains a field called errors
or not. 您应该将响应主体解析为JSON对象,并检查JSON是否包含一个称为
errors
的字段。
If you have Jackson
in the class path , RestTemplate
will detect it and auto configure itself to be able to parse JSON which allows you to do something like: 如果您在类路径中有
Jackson
,则RestTemplate
将检测到它并自动配置为能够解析JSON,从而可以执行以下操作:
ResponseEntity<Map<String,Object>> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
Map<String,Object> body = response.getBody();
if(body.containsKey("errors")){
//handleException
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.