【问题标题】:Prevent console error with Mongoose, node and graphql使用 Mongoose、node 和 graphql 防止控制台错误
【发布时间】:2017-08-17 20:27:23
【问题描述】:

我正在使用 Express、Graphql(Apollo 服务器)和猫鼬制作 API 服务器。

我正在测试用户创建。当电子邮件重复时,mongoose 会引发错误(验证错误。唯一 = true)并且 graphql 处理得非常好。但控制台(终端)也显示错误。我怎样才能防止这个问题?

解析器:

const MODEL_PATH = '../../models';
const User = require(MODEL_PATH + '/User');
const { register } = require('../../controllers/auth/RegisterController');

module.exports = {
  RootQuery: {
    users() {
      return User.find({});
    }
  },
  Mutation: {
    registerUser(_, data) {
      return register(data);
    }
  }
};

RegisterController(注册函数)

exports.register = function(data) {
  const { email, password } = data;

  const user = new User({
    email,
    password
  });

  return new Promise((resolve, reject) => {
    user.save().then((user) => {
      resolve(user);
    }).catch((err) => {
      reject(err);
    });
  });

};

还有控制台中的错误(我不想要那个。我处理了控制器中的错误。我只想要图形响应中的错误)

MongoError: E11000 duplicate key error collection: y.users index: email_1 dup key: { : "test@example.com" }
    at Function.MongoError.create (/Volumes/Datos/x/code/y/server/node_modules/mongodb-core/lib/error.js:31:11)
    at toError (/Volumes/Datos/x/code/y/server/node_modules/mongodb/lib/utils.js:114:22)
   ....

Graphiql 中的响应(没关系)

{
  "data": {
    "registerUser": null
  },
  "errors": [
    {
      "message": "E11000 duplicate key error collection: y.users index: email_1 dup key: { : \"test@example.com\" }",
      "locations": [
        {
          "line": 9,
          "column": 3
        }
      ],
      "path": [
        "registerUser"
      ]
    }
  ]
}

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose graphql apollo


    【解决方案1】:

    根据:http://dev.apollodata.com/tools/graphql-server/setup.html

    在服务器中

    app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: myschema, debug: false }));
    

    debug false 成功了。

    现在。我正在检查软件包以获得更好的错误处理

    谢谢

    【讨论】:

      【解决方案2】:

      查看apollo-errors:

      https://github.com/thebigredgeek/apollo-errors

      apollo-resolvers:

      https://github.com/thebigredgeek/apollo-resolvers

      这些软件包一起用于处理您描述的问题

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 1970-01-01
        • 2023-01-02
        • 2016-03-12
        • 2021-10-14
        • 1970-01-01
        • 2012-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多