据我了解,您可以在graphql和graphql-express中创建自定义错误。

https://codeburst.io/custom-errors-and-error-reporting-in-graphql-bbd398272aeb

我创建了一个自定义的Error实现,但是添加的属性在途中丢失,并且永远无法到达formatError函数,我是否缺少某些东西,或者这是一个错误?

示例代码:

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');


查询网址:

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"
  }
}

最佳答案

发生异常时,错误会再次包装在GraphQLError


  返回新的_GraphQLError.GraphQLError(originalError && originalError.message,originalError && originalError.nodes ||节点,originalError && originalError.source,originalError && originalError.positions,path,originalError);


因此,您的实际错误在originalError中。因此,如果我将您的控制台更改为

  console.log(err.originalError.customField); // => undefined


我得到正确的输出

javascript - graphql-js和express的自定义错误-LMLPHP

10-06 12:13