我怎样才能返回多个这样的错误消息?
"errors": [
{
"message": "first error",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"somePath"
]
},
{
"message": "second error",
"locations": [
{
"line": 8,
"column": 9
}
],
"path": [
"somePath"
]
},
]
在我的服务器上,如果我执行 throw('an error')
,它会返回。
"errors": [
{
"message": "an error",
"locations": [
{
}
],
"path": ["somePath"]
}
]
我想返回查询中所有错误的数组。
如何向 errors
数组添加多个错误?
最佳答案
抛出一个带有 errors:[]
的错误对象。错误数组应该包含您想要汇总的所有错误。使用 formatError
函数来格式化错误输出。在下面的示例中,我使用的是 Apollo UserInputError
。您也可以使用 GraphQLError
。没关系。
const error = new UserInputError()
error.errors = errorslist.map((i) => {
const _error = new UserInputError()
_error.path = i.path
_error.message = i.type
return _error
})
throw error
new ApolloServer({
typeDefs,
resolvers,
formatError: ({ message, path }) => ({
message,
path,
}),
})
//sample output response
{
"data": {
"createUser": null
},
"errors": [
{
"message": "format",
"path": "username"
},
{
"message": "min",
"path": "phone"
}
]
}
关于node.js - 如何使用 graphQL 返回错误数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44130930/