Пользовательские ошибки с graphql-js и express - PullRequest
0 голосов
/ 17 мая 2018

Насколько я понимаю, вы можете создавать собственные ошибки в 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"
  }
}

1 Ответ

0 голосов
/ 24 мая 2018

Когда возникает исключение, ошибка снова переносится в GraphQLError

return new _GraphQLError.GraphQLError (originalError && originalError.message, originalError && originalError.nodes || узлы, originalError && originalError.source, originalError && originalError.positions, path, originalError);

Таким образом, ваша фактическая ошибка в originalError.Поэтому, если я изменю вашу консоль на

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

, я получу правильный вывод

Error custom fields

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...