如何使用graphQL返回错误数组

Lev*_*Lev 11 node.js hapijs graphql

如何返回这样的多个错误消息?

"errors": [
  {
    "message": "first error",
    "locations": [
      {
        "line": 2,
        "column": 3
      }
    ],
    "path": [
      "somePath"
    ]
  },
  {
    "message": "second error",
    "locations": [
      {
        "line": 8,
        "column": 9
      }
    ],
    "path": [
      "somePath"
    ]
  },
]
Run Code Online (Sandbox Code Playgroud)

在我的服务器上,如果我这样做throw('an error'),它会返回.

"errors": [
  {
    "message": "an error",
    "locations": [
      {
      }
    ],
    "path": ["somePath"]
  }
]
Run Code Online (Sandbox Code Playgroud)

我想返回查询中所有错误的数组.如何向errors阵列添加多个错误?

mat*_*vio 0

您需要在没有throw语句的情况下捕获错误,因为您不想中断进程。相反,您可以创建一个名为“errors”的数组,并将.push()错误放入其中。当您认为合适时,在过程接近结束时,您可以检查错误数组内是否有错误。如果有,您可以根据需要显示或处理它们

// example
var errors = [];

doSomething(function(err,res){

    if(err){
        errors.push(err);
    }
    console.log("we did a thing");
    doSomethingElse(function(err,res2){

         if(err){
              errors.push(err);
         };
         console.log("we did another thing");

         // check and throw errors
         if(errors.length > 0){
             throw errors;
         }



    });

});
Run Code Online (Sandbox Code Playgroud)