Javascript graphql js和express的自定义错误
据我所知,您可以在graphql和graphql express中创建自定义错误 我已经创建了一个自定义错误实现,但是添加的属性在运行过程中丢失了,并且从未到达formatError函数,我是缺少了什么还是这是一个bug 示例代码:Javascript graphql js和express的自定义错误,javascript,node.js,graphql,Javascript,Node.js,Graphql,据我所知,您可以在graphql和graphql express中创建自定义错误 我已经创建了一个自定义错误实现,但是添加的属性在运行过程中丢失了,并且从未到达formatError函数,我是缺少了什么还是这是一个bug 示例代码: var express = require('express'); var graphqlHTTP = require('express-graphql'); var { buildSchema, GraphQLError } = require('graphql
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema, GraphQLError } = require('graphql');
// i tried extending just from Error with the same results
class CustomError extends GraphQLError {
constructor(message) {
super(message);
this.customField = 'nopesies';
}
}
var schema = buildSchema(`
type Query {
hello: String
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
const err = new CustomError('i am special')
console.log(err.customField); // => nopesies
throw err
},
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
formatError(err) {
console.log(err.customField); // => undefined
return {
message: err.message,
thisIsFine: 'grmpf',
locations: err.locations,
path: err.path,
customField: err.customField,
};
},
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
查询Url:
Package.json:
{
"name": "custom-graphql-errors",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"express": "^4.16.3",
"express-graphql": "^0.6.12",
"graphql": "^0.13.2"
}
}
发生异常时,错误将再次包装在
GraphQLError
返回新的_graphqleror.graphqleror(originalError&&originalError.message,originalError&&originalError.nodes | | |节点,originalError&&originalError.source,originalError&&originalError.positions,path,originalError)
因此,您的实际错误在原始错误中。所以如果我把你的控制台换成
console.log(err.originalError.customField); // => undefined
我得到了正确的输出