如何用express-graphql引发多个错误?

Fra*_*ain 2 javascript graphql graphql-js express-graphql

在express-graphql应用程序中,我有一个userLogin解析器,如下所示:

const userLogin = async ({ id, password }), context, info) => {

    if (!id) {
      throw new Error('No id provided.')
    }

    if (!password) {
      throw new Error('No password provided.')
    }

    // actual resolver logic here
    // … 
}
Run Code Online (Sandbox Code Playgroud)

如果用户不提供idAND AND password,则只会抛出一个错误。

{
  "errors": [
    {
      "message": "No id provided.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "userLogin"
      ]
    }
  ],
  "data": {
    "userLogin": null
  }
}
Run Code Online (Sandbox Code Playgroud)

如何在errors响应数组中引发多个错误?

Dan*_*den 5

无法在JavaScript中引发一系列错误,否则无法通过单个解析器拒绝多个错误。GraphQL响应包括一个errors数组,而不仅仅是单个error对象,因为当这些错误来自不同字段时,总响应可能包含多个错误。考虑以下架构和解析器:

type Query {
  a: String
  b: String
  c: String
}

const resolvers = {
  Query: {
    a: () => { throw new Error('A rejected') },
    b: () => { throw new Error('B rejected') },
    c: () => 'Still works!',
  },
}
Run Code Online (Sandbox Code Playgroud)

如果查询所有三个字段...

查询{a b c}

您的数据将如下所示:

{
  "errors": [
    {
      "message": "A rejected",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "a"
      ]
    },
    {
      "message": "B rejected",
      "locations": [
        {
          "line": 3,
          "column": 3
        }
      ],
      "path": [
        "b"
      ]
    }
  ],
  "data": {
    "a": null,
    "b": null,
    "c": "Still works!"
  }
}
Run Code Online (Sandbox Code Playgroud)

这是因为GraphQL支持部分响应。但是,请记住,这是可行的,因为这些字段可以为空。如果它们不是null,那么这些错误将冒泡到最接近的nullable父字段

以下是一些替代方法:

您可以利用它formatError来改变GraphQL返回的错误显示给客户端的方式。这意味着您可以在错误中包括任何种类的额外信息,例如错误代码或多个错误消息。一个简单的例子:

// The middleware
app.use('/graphql', graphqlExpress({
    schema: schema,
    formatError: (error) => ({
      message: error.message,
      path: error.path,
      locations: error.locations,
      errors: error.originalError.details
    })
}))

// The error class
class CustomError extends Error {
  constructor(detailsArray) {
    this.message = String(details)
    this.details = details
  }
}

// The resolver
const userLogin = async ({ id, password }), context, info) => {
    const errorDetails = []
    if (!id) errorDetails.push('No id provided.')
    if (!password) errorDetails.push('No password provided.')
    if (errorDetails.length) throw new CustomError(errorDetails)

    // actual resolver logic here
}
Run Code Online (Sandbox Code Playgroud)

然后您的响应看起来像这样:

{
  "errors": [
    {
      "message": "[No id provided.,No password provided.]",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "userLogin"
      ]
      "errors" [
        "No id provided.",
        "No password provided."
      ]
    }
  ],
  "data": {
    "userLogin": null
  }
}
Run Code Online (Sandbox Code Playgroud)

就是说,返回面向用户的错误消息以及GraphQL验证错误有点不愉快。一些API采取的另一种方法是errors在实际的突变响应旁边添加一个字段。例如:

type Mutation {
  userLogin: UserLoginResponse
}

type UserLoginResponse {
  response: User
  errors: [String!]
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用并集实现类似的效果:

type Mutation {
  userLogin: UserLoginResponse
}

type Errors {
  errors: [String!]!
}

union UserLoginResponse = User | Errors
Run Code Online (Sandbox Code Playgroud)