我从 GraphQL 开始,我无法理解如何在 GraphQL 中抛出错误
我浏览了网络上的几篇文章,但几乎所有文章都使用 Apollo,而且代码结构看起来与我的工作方式大不相同。
考虑这段代码,我在这里进行突变,现在如何发送带有错误的响应消息并在出现错误时更改 header 状态消息?
AddNewPersonalInfo: {
type: userDashboardType,
args: {
parameter: {
type: userCreationlInputType
}
},
resolve: async (parent, args, context) => {
args.parameter.userId = context.req.headers.userId
//Check if user info already exsist
const checkIfUserInformationExsist = await getSelectedThingFromTable('CatsWork_personal', 'userId', `${userId}`)
if (checkIfUserInformationExsist[0]) {
const error = {
code: 403,
message: 'User info Already exsist'
}
throw new Error(error)
} else {
try {
const addLinkedinUser = await insertIntheTable('personal', payload)
return true
} catch (err) {
console.error(err)
throw new Error(err)
}
}
}
}
最佳答案
我在我的一个项目中遇到过,很难设置响应的状态码。因此,我使用 express-graphql 进行了一些自定义错误响应以识别正确的 statusCode
以下是示例(我在其中一个项目中使用的):
--------app.js 文件
--------
const graphqlHTTP = require('express-graphql')
app.use('/graphql', (req, res) => {
graphqlHTTP({
schema: GraphQLSchema, //A GraphQLSchema instance from GraphQL.js. A schema must be provided.
graphiql: true,
context: { req },
formatError: (err) => {
const error = getErrorCode(err.message)
return ({ message: error.message, statusCode: error.statusCode })
}
})(req, res)
})
--------getErrorCode
函数实现--------
const { errorType } = require('../constants')
const getErrorCode = errorName => {
return errorType[errorName]
}
module.exports = getErrorCode
--------Constant.js
文件--------
exports.errorName = {
USER_ALREADY_EXISTS: 'USER_ALREADY_EXISTS',
SERVER_ERROR: 'SERVER_ERROR'
}
exports.errorType = {
USER_ALREADY_EXISTS: {
message: 'User is already exists.',
statusCode: 403
},
SERVER_ERROR: {
message: 'Server error.',
statusCode: 500
}
}
现在,我们可以使用我们的设置了。
从您的查询或突变中,您需要需要常量文件并返回自定义错误:
const { errorName } = require('../constant')
AddNewPersonalInfo: {
type: userDashboardType,
args: {
parameter: {
type: userCreationlInputType
}
},
resolve: async (parent, args, context) => {
args.parameter.userId = context.req.headers.userId
//Check if user info already exsist
const checkIfUserInformationExsist = await getSelectedThingFromTable('CatsWork_personal', 'userId', `${userId}`)
if (checkIfUserInformationExsist[0]) {
const error = {
code: 403,
message: 'User info Already exsist'
}
throw new Error(errorName.USER_ALREADY_EXISTS) // Here you can use error from constatnt file
} else {
try {
const addLinkedinUser = await insertIntheTable('personal', payload)
return true
} catch (err) {
console.error(err)
throw new Error(errorName.SERVER_ERROR) // Here you can use error from constatnt file
}
}
}
}
--------错误响应--------
{
error: [{
"statusCode": 403,
"message": "User is already exists."
}],
data: null
}
我们也只需要从 FS 端编写自定义错误处理。
Note:-
formatError:
is deprecated and replaced bycustomFormatErrorFn
. It will be removed in version 1.0.0. You can refer customFormatErrorFn.
关于javascript - 如何在 GraphQL 中处理错误并发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342284/