5

假设我正在尝试创建一辆自行车作为突变

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)
    }
  })
})

是否像返回服务器/我定义的某些错误类型一样简单?

4

1 回答 1

7

不完全确定这是否是你所追求的......

只需抛出一个新错误,它应该返回类似

{
  "data": {
    "createBike": null
  },
  "errors": [
    {
      "message": "Not enough metal",
      "originalError": {}
    }
  ]
}

您的客户端应该只处理响应

if (res.errors) {res.errors[0].message}

我所做的是传递一个带有 errorCode 和消息的对象,在这个阶段,最好的方法是对其进行字符串化。

throw new Errors(JSON.stringify({
      code:409, 
      message:"Duplicate request......"
}))

注意:您也可能对此库感兴趣https://github.com/kadirahq/graphql-errors

您可以屏蔽所有错误(将消息转为“内部错误”),或定义 userError('message to the client'),这些不会被替换。

于 2016-04-05T16:29:54.073 回答