Reputation: 3342
From my understanding you can create custom errors in graphql and graphql-express.
https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb
I have created a custom Error implementation, but the added properties are lost on the way down and never reach the formatError function, am i missing something or is this a bug?
Example code:
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');
Query-Url:
http://localhost:4000/graphql?query=%7B%0A%20%20hello%0A%7D
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"
}
}
Upvotes: 1
Views: 2080
Reputation: 146490
When an exception occurs the error is wrapped again in a GraphQLError
return new _GraphQLError.GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError);
So your actual error is in originalError
. So if I change your console to
console.log(err.originalError.customField); // => undefined
I get correct output
Upvotes: 2