gpt4 book ai didi

json - GraphQL java以json格式发送自定义错误

转载 作者:行者123 更新时间:2023-12-04 19:27:24 27 4
gpt4 key购买 nike

我在一个 graphql 应用程序中工作,我必须在 json 中发送自定义错误对象/消息,而不管它是发生在 servlet 还是服务中。

预期的错误响应
{ errorCode: 400 //error goes here,
errorMessage: "my error mesage"}

如果有人可以指导我实现上述要求,那将很有帮助。

最佳答案

GraphQL specificationerror 定义了清晰的格式响应中的条目。

根据规范,它应该是这样的(假设使用 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
}
}
]

the 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<String, Object> getExtensions() {
Map<String, Object> customAttributes = new LinkedHashMap<>();

customAttributes.put("errorCode", this.errorCode);
customAttributes.put("errorMessage", this.getMessage());

return customAttributes;
}

@Override
public List<SourceLocation> getLocations() {
return null;
}

@Override
public ErrorType getErrorType() {
return null;
}
}

然后你可以抛出异常,从你的数据 getter 内部传入代码和消息:
throw new CustomException(400, "A custom error message");

现在,有另一种方法来解决这个问题。

假设您正在开发一个 Web 应用程序,您 可以 以您想要的任何格式返回错误(和数据,就此而言)。虽然在我看来这有点尴尬。 GraphQL 客户端,如 Apollo,遵守规范,那么你为什么要以任何其他格式返回响应?但无论如何,那里有很多不同的要求。

一旦您获得 ExecutionResult ,您可以以您想要的任何格式创建 map 或对象,将其序列化为 JSON 并通过 HTTP 返回。
Map<String, Object> result = new HashMap<>();

result.put("data", executionResult.getData());

List<Map<String, Object>> errors = executionResult.getErrors()
.stream()
.map(error -> {
Map<String, Object> errorMap = new HashMap<>();

errorMap.put("errorMessage", error.getMessage());
errorMap.put("errorCode", 404); // get the code somehow from the error object

return errorMap;
})
.collect(toList());

result.put("errors", errors);

// Serialize "result" and return that.

但同样,在大多数情况下,做出不符合规范的响应是没有意义的。

关于json - GraphQL java以json格式发送自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083930/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com