如何实现多个项目的GraphQL错误处理?
我一直在学习GraphQl,现在我正在学习与GraphQL中错误处理有关的内容。我提到本文。现在,从文章中我了解到,如果我在GraphQl中有一个user
查询,那么我可以建立一个联合,其中包含所有可能的类型,包括error
union uneRESULT = useresult = user | deleteduser |错误
现在,在该特定解析器中,如果发生任何错误,我将发送错误类型响应,我将能够在客户端显示适当的错误。那就是错误处理。
但是,如果我有一个查询用户
,该将返回一系列用户。 我将做类似的事情。
type Query {
users: [UserResult!]!
}
union UserResult = User | DeletedUser | Error
假设通过遵循上述方法, 因为,GraphQl不允许这样的语法...
type Query {
users: UsersResult!
}
union UserResult = User | DeletedUser | Error
union UsersResult = [UserResult!] | Error
那么,我将如何在GraphQl中实现此功能?
我期望的响应是...
如果什么都没有问题...
data: {
users: [
{ id: '1', username: 'user1', email: '[email protected]' },
{ id: '2', username: 'user2', email: '[email protected]' },
{ id: '3', username: 'user3', email: '[email protected]' }
]
}
如果在数据库中获取数据时出现问题(例如)...
data: {
error: {
code: 'ER101',
message: 'Something went wrong',
}
}
I have been learning GraphQL and right now I am learning things related to Error Handling in GraphQL. I referred to this article for Error Handling in GraphQL. Now, from Article I understand that If I have a user
query in GraphQL then I can make an Union which will contain all possible types including Error
union UserResult = User | DeletedUser | Error
Now, In that particular resolver if any error would occur then I will send an Error type Response and I'll be able to show appropriate error on Client Side. and Thats the Error Handling.
But what If I have a query users
which will return an Array of Users. Suppose by following the above approach I will be doing something like...
type Query {
users: [UserResult!]!
}
union UserResult = User | DeletedUser | Error
Now, In users
resolver if any error would occur then I wont be able to send back a single Error Response. Because, GraphQL does not allow such syntax...
type Query {
users: UsersResult!
}
union UserResult = User | DeletedUser | Error
union UsersResult = [UserResult!] | Error
So, How am I gonna achieve this functionality in GraphQL?
The Response I expect is...
If nothing goes wrong...
data: {
users: [
{ id: '1', username: 'user1', email: '[email protected]' },
{ id: '2', username: 'user2', email: '[email protected]' },
{ id: '3', username: 'user3', email: '[email protected]' }
]
}
If something goes wrong while fetching data from database(for instance)...
data: {
error: {
code: 'ER101',
message: 'Something went wrong',
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会做这样的事情,以保持文章:
然后,您可以处理这样的错误:
这也取决于您的用例和业务逻辑。
I would do something like this, to keep the benefits explained in the article:
You can then handle errors like this:
It also depends on your use cases and business logic.
不确定这是否会解决您的情况:
这取决于您的用例,因为您的用户是一个数组,并且错误仅包含一条消息,我想错误可以结束到一个错误并告知客户端吗?
Not sure if this will solve your case:
It's up to your use case, since your users is an array, and error only contains one message, I suppose errors can be concluded to one single error and inform client?