使用graphql-js和express定制错误

时间:2018-05-17 12:32:16

标签: javascript node.js graphql

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

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

我已经创建了一个自定义的错误实现,但添加的属性在向下的路上丢失,永远不会到达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');

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

1 个答案:

答案 0 :(得分:1)

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

  

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

所以你的实际错误在originalError。所以,如果我将你的控制台改为

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

我得到正确的输出

Error custom fields

相关问题