处理突变中的错误
Handling errors in mutations
假设我正在尝试制造一辆自行车作为变异
var createBike = (wheelSize) => {
if (!factoryHasEnoughMetal(wheelSize)) {
return supplierError('Not enough metal');
}
return factoryBuild(wheelSize);
}
当没有足够的钢材来制造闪亮的轮子时会发生什么?我们可能需要一个客户端错误。我如何通过以下突变从我的 graphQL 服务器将其提供给他们:
// Mutations
mutation: new graphql.GraphQLObjectType({
name: 'BikeMutation',
fields: () => ({
createBike: {
type: bikeType,
args: {
wheelSize: {
description: 'Wheel size',
type: new graphql.GraphQLNonNull(graphql.Int)
},
},
resolve: (_, args) => createBike(args.wheelSize)
}
})
})
是否像返回 server/I 定义的错误类型一样简单?
不确定这是否是您想要的...
只是抛出一个新的错误,它应该return类似于
{
"data": {
"createBike": null
},
"errors": [
{
"message": "Not enough metal",
"originalError": {}
}
]
}
您的客户端应该只处理响应
if (res.errors) {res.errors[0].message}
我所做的是传递一个带有errorCode和message的对象,在这个阶段,最好的方法是将它字符串化。
throw new Errors(JSON.stringify({
code:409,
message:"Duplicate request......"
}))
注意:您也可能对此库感兴趣 https://github.com/kadirahq/graphql-errors
您可以屏蔽所有错误(将消息转为 "Internal Error"),或定义 userError('message to the client'),这些不会被替换。
假设我正在尝试制造一辆自行车作为变异
var createBike = (wheelSize) => {
if (!factoryHasEnoughMetal(wheelSize)) {
return supplierError('Not enough metal');
}
return factoryBuild(wheelSize);
}
当没有足够的钢材来制造闪亮的轮子时会发生什么?我们可能需要一个客户端错误。我如何通过以下突变从我的 graphQL 服务器将其提供给他们:
// Mutations
mutation: new graphql.GraphQLObjectType({
name: 'BikeMutation',
fields: () => ({
createBike: {
type: bikeType,
args: {
wheelSize: {
description: 'Wheel size',
type: new graphql.GraphQLNonNull(graphql.Int)
},
},
resolve: (_, args) => createBike(args.wheelSize)
}
})
})
是否像返回 server/I 定义的错误类型一样简单?
不确定这是否是您想要的...
只是抛出一个新的错误,它应该return类似于
{
"data": {
"createBike": null
},
"errors": [
{
"message": "Not enough metal",
"originalError": {}
}
]
}
您的客户端应该只处理响应
if (res.errors) {res.errors[0].message}
我所做的是传递一个带有errorCode和message的对象,在这个阶段,最好的方法是将它字符串化。
throw new Errors(JSON.stringify({
code:409,
message:"Duplicate request......"
}))
注意:您也可能对此库感兴趣 https://github.com/kadirahq/graphql-errors
您可以屏蔽所有错误(将消息转为 "Internal Error"),或定义 userError('message to the client'),这些不会被替换。