如何在 graphql apollo-server 突变解析器中发出错误信号?

How can I signal an error in a graphql apollo-server mutation resolver?

documentation 告诉我们解析器具有以下形式:

fieldName: (obj, args, context, info) => result

结果是 nullundefined 如果 "the object could not be found"。

其他错误怎么办 - 例如,如果访问未经授权?

看来您不能直接"return"一个错误,因为结果必须与模式匹配。

我试过在解析器中抛出一个异常,这几乎是正确的:客户端收到一个带有异常消息的 ApolloError:太好了。但是 apollo 服务器发出堆栈跟踪,就好像没有处理异常一样。好像不太对。

因此问题:应该如何完成?


apollo 服务器堆栈跟踪,以防有帮助:

Error: test exception message
at /Users/mgregory/NRN/src/agreeonit/apollo_server/resolvers/mutationResolvers.js:29:17
at tryCatcher (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/promise.js:691:18)
at Async._drainQueue (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues (/Users/mgregory/NRN/src/agreeonit/apollo_server/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:574:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5)

我发现正在发出堆栈跟踪,因为 GraphQLOptions.debug 的默认设置是 true

在服务器初始化时将其设置为 false 会清理所有内容。

结论:抛出异常才是正确的做法。