【发布时间】:2021-01-15 15:33:12
【问题描述】:
我有一个正在运行的 apollo graphql express 服务器。唯一的问题是 express 抱怨我在用来验证 jwt 令牌的 Promise 上没有 catch 块:
(node:96074) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺
我可以在 promise 中添加一个 catch 块,但是当令牌失效时它会返回 pending 而不是 rejected。这会导致身份验证流程中断,因为我的 graphql 解析器依赖该拒绝来阻止对数据库的访问。
这就是我用于身份验证的 auth0 建议设置它的方式。他们只是没有提到 UnhandledPromiseRejectionWarning。
代码如下所示:
//server def
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => {
if (req.headers.authorization) {
const token = req.headers.authorization.split(' ')[1];
//THE PROMISE IN QUESTION
const authUserObj = new Promise((resolve, reject) => {
jwt.verify(token, getKey, options, (err, decoded) => {
if (err) {
reject(err);
}
if (decoded) {
resolve(decoded);
}
});
});
return {
authUserObj
};
}
},
introspection: true,
playground: true
});
//a graphql resolver that gets the rejection via authUserObj and catches the error
addUser: async (parent, args, {authUserObj}) => {
try {
const AuthUser = await authUserObj;
const response = await User.create(args);
return response;
} catch(err) {
throw new AuthenticationError('You must be logged in to do this');
}
}
一切正常...除了我希望克服的那个烦人的节点错误!所以我在 promise 中添加了一个 catch 块:
const authUserObj = new Promise((resolve, reject) => {
jwt.verify(token, getKey, options, (err, decoded) => {
if (err) {
console.log("-------rejected-------", err.message)
reject(err);
}
if (decoded) {
console.log("-------decoded-------")
resolve(decoded);
}
});
}).catch( err => { return err.message});
现在 authUserObj 不是返回被拒绝,而是处于挂起状态,任何人都可以添加用户,这违背了 auth 的目的。
如果有人知道如何在仍然拒绝该错误的同时捕获该错误,我会全力以赴。谢谢。
【问题讨论】:
标签: javascript node.js error-handling promise graphql