【发布时间】:2020-04-23 02:09:21
【问题描述】:
鉴于以下 GraphQL 突变:
type Mutation {
updateUser(id: ID!, newEmail: String!): User
updatePost(id: ID!, newTitle: String!): Post
}
Apollo 文档指出,完全有可能在一个请求中执行多个突变,比如说
mutation($userId: ID!, $newEmail: String!, $postId: ID!, $newTitle: String!) {
updateUser(id: $userId, newEmail: $newEmail) {
id
email
}
updatePost(id: $postId, newTitle: $newTitle) {
id
title
}
}
1.真的有人这样做吗?如果你不明确地这样做,批处理会导致这种突变合并吗?
2。如果您在突变中执行多个操作,您将如何正确处理错误?
我看到很多人建议在服务器上抛出错误,以便服务器响应如下所示:
{
errors: [
{
statusCode: 422,
error: 'Unprocessable Entity'
path: [
'updateUser'
],
message: {
message: 'Validation failed',
fields: {
newEmail: 'The new email is not a valid email address.'
}
},
},
{
statusCode: 422,
error: 'Unprocessable Entity'
path: [
'updatePost'
],
message: {
message: 'Validation failed',
fields: {
newTitle: 'The given title is too short.'
}
},
}
],
data: {
updateUser: null,
updatePost: null,
}
}
但是我怎么知道哪个错误属于哪个突变?我们不能假设errors 数组中的第一个错误属于第一个突变,因为如果updateUser 成功,该数组将简单地包含一个条目。然后我是否必须遍历所有错误并检查路径是否与我的突变名称匹配? :D
另一种方法是将错误包含在专用响应类型中,例如 UpdateUserResponse 和 UpdatePostResponse。这种方法使我能够正确解决错误。
type UpdateUserResponse {
error: Error
user: User
}
type UpdatePostResponse {
error: Error
post: Post
}
但我有一种感觉,这会使我的架构膨胀很多。
【问题讨论】:
标签: error-handling graphql mutation