首页 > 解决方案 > 无法在 ApolloServer 中抛出错误,在捕捉到 Cognito 错误时未处理的承诺拒绝

问题描述

为 GraphQL API 创建我的第一个用户注册解析器。

当我从解析器中点击它时,我无法从 Cognito API 获取错误响应。

错误日志如下所示,将对应于下面的解析器代码。

{ data: { registerUser: null } }
error is here
{ code: 'UsernameExistsException',
  name: 'UsernameExistsException',
  message: 'An account with the given email already exists.' }
error is here
{ code: 'UsernameExistsException',
  name: 'UsernameExistsException',
  statusCode: 400,
  message: '400' }

我已经确定了以下几点: - 解析器正在被沙箱和客户端命中。- 我已将 ApolloServer 配置为 formatResponses 和 Errors

配置代码

const server = new ApolloServer({
typeDefs: [rootSchema, ...schemaTypes],
resolvers: merge({}, user),
async context({ req }) {
  const user = await authenticate(req)
  return { user }
},
formatResponse: response => {
        console.log(response);
        return response;
 },
formatError: error => ({
         message: error.message,
     state: error.originalError && error.originalError.state,
        locations: error.locations,
        path: error.path,
    })

});

const registerUser = (_, args, ctx) => {
var attributeList = [];
console.log('args')
console.log(args)

var params = {
    ClientId: "config.clientId",
    Password: args.user.password,
    Username: args.user.username,
    UserAttributes: attributeList
}
    userPool.signUp(args.user.email, args.user.password, attributeList, null, function(err, result){
        if (err) {
            console.log('error is here')
            console.log(err);
            throw new Error(err.message);
        }

        if(result) {
            console.log('result is here')
            console.log(result)
            cognitoUser = result.user;

        }

    }).catch(function(error) {
        console.log('error is below');
        console.log(error);
        return error;
    })

}

有两件事阻止我前进。当我从 userPool 承诺中省略 catch 块时,我根本没有收到任何错误,错误不是从 signUp 函数内部抛出的。

如果我从解析器中抛出任何错误(无论是在回调还是在 catch 块中),我都会收到以下错误。

at process._tickCallback (internal/process/next_tick.js:160:7)
(node:28342) UnhandledPromiseRejectionWarning: Unhandled promise 
rejection. This error originated either by throwing inside of an async 
function without a catch block, or by rejecting a promise which was not 
handled with .catch(). (rejection id: 1)
(node:28342) [DEP0018] DeprecationWarning: Unhandled promise rejections 
are deprecated. In the future, promise rejections that are not handled 
will terminate the Node.js process with a non-zero exit code.

我想让以下错误返回到沙箱/请求者

{ data: { registerUser: null } }
error is here
{ code: 'UsernameExistsException',
  name: 'UsernameExistsException',
  message: 'An account with the given email already exists.' }

谢谢你的帮助。

标签: javascriptnode.jsgraphqlamazon-cognitoapollo-server

解决方案


弄清楚了。AWS API 仅限于回调实施。将您的回调包装为一个承诺 - 然后根据需要链接该承诺抛出。


推荐阅读