捕获Cognito错误时无法在ApolloServer中引发错误,无法处理的承诺被拒绝

时间:2018-12-29 21:08:03

标签: javascript node.js graphql amazon-cognito apollo-server

为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配置为格式化响应和错误

配置代码

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.' }

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

弄清楚了。 AWS API仅限于回调实现。将回调包装为一个Promise-然后将Promise链接到需要的链结。