作者:傻缺缺的谭贱儿_452 | 来源:互联网 | 2022-12-06 11:58
我在graphql应用程序中工作,无论它是否出现在servlet或服务中,我都必须在json中发送自定义错误对象/消息。
预期的错误响应
{ errorCode: 400 //error goes here,
errorMessage: "my error mesage"}
如果有人可以指导我达到上述要求,将会很有帮助。
1> felipe_gdr..:
GraphQL规范为error
响应中的条目定义了清晰的格式。
根据规范,它应该像这样(假设使用JSON格式):
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ]
"extensions": {/* You can place data in any format here */}
}
]
因此,您将找不到允许您对其进行扩展并在GraphQL执行结果中返回诸如此类的GraphQL实现,例如:
"errors": [
{
"errorMessage": "Name for character with ID 1002 could not be fetched.",
"errorCode": 404
}
]
但是,该规范允许您以任何格式在extension
条目中添加数据。因此,您可以在服务器端创建一个自定义Exception并最终得到一个类似于JSON的响应:
"errors": [
{
"message": "Name for character with ID 1002 could not be fetched.",
"locations": [ { "line": 6, "column": 7 } ],
"path": [ "hero", "heroFriends", 1, "name" ]
"extensions": {
"errorMessage": "Name for character with ID 1002 could not be fetched.",
"errorCode": 404
}
}
]
如docs中所述,在GraphQL Java上实现它非常容易。您可以创建一个覆盖该getExtensions
方法的自定义异常,并在实现内部创建一个映射,然后将其用于构建以下内容extensions
:
public class CustomException extends RuntimeException implements GraphQLError {
private final int errorCode;
public CustomException(int errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
}
@Override
public Map getExtensions() {
Map customAttributes = new LinkedHashMap<>();
customAttributes.put("errorCode", this.errorCode);
customAttributes.put("errorMessage", this.getMessage());
return customAttributes;
}
@Override
public List getLocations() {
return null;
}
@Override
public ErrorType getErrorType() {
return null;
}
}
那么您可以从数据读取器内部引发代码和消息中传递的异常:
throw new CustomException(400, "A custom error message");
现在,有另一种解决方法。
假设您正在使用Web应用程序,则可以按所需的任何格式返回错误(以及相关的数据)。虽然在我看来这有点尴尬。GraphQL客户端(如Apollo)遵守该规范,那么为什么要返回任何其他格式的响应?但是无论如何,那里有很多不同的要求。
拥有时ExecutionResult
,您可以按所需的格式创建地图或对象,将其序列化为JSON并通过HTTP返回。
Map result = new HashMap<>();
result.put("data", executionResult.getData());
List
但是同样,在大多数情况下,做出不符合规范的回应是没有意义的。