【发布时间】:2019-05-27 03:41:23
【问题描述】:
为 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.' }
感谢您的帮助。
【问题讨论】:
-
欢迎来到 Stack Overflow。我认为您不需要抛出错误,您应该返回带有错误代码的数据
-
@Mikkel - 谢谢!当我简单地返回错误时,它不会进入响应。
标签: javascript node.js graphql amazon-cognito apollo-server