The following code snippet causes an "Uncaught exception warning" when reject(err) is called, although the method is called inside a try/catch statement.
async verifyToken (token: string): Promise<string | object> {
return new Promise<string | object>( (resolve, reject) => {
jwt.verify(token, this._publicKey, (err, decoded) => {
if (err) {
reject(err);
} else {
resolve(decoded);
};
});
}
This violates my understanding about promisses and the async/await pattern, because up to now I do not expect an unhandling error if the function is called inside a try/catch statement.
try {
const obj = await verifyToken(token);
} catch (err) {
...
}
At the moment I avoid this problem with a work arround.
async verifyToken (token: string): Promise<string | object> {
let cause: any;
const rv = await new Promise<string | object>( (resolve, reject) => {
jwt.verify(token, this._publicKey, (err, decoded) => {
if (err) {
cause = err;
resolve(undefined);
} else {
resolve(decoded);
};
})
});
if (rv) {
return rv;
} else if (cause instanceof Error) {
throw cause;
} else {
throw new Error('invalid token');
}
}
My questions:
I know this is old, and I'm sorry but I just stumbled upon this a moment ago searching for something else, but I think I have the answer to this specific problem.
Promise will neither resolve nor reject in the cast that jwt.verify() throws its own error. Guessing that the lib is jsonwebtoken or something like that I suspect that you have passed an invalid token and that the method does a throw new Error('Invalid token')
I think further to that you're mixing some ideas if you are going to return a new Promise you likely shouldn't use the async keyword.
Suggestion,
function verifyToken(token: string): Promise<ABetterType> {
return new Promise((resolve, reject) => {
try {
jwt.verify(token, this._publicKey, (err, decoded) => {
if (err) {
reject(err)
return;
}
resolve(decoded)
}
} catch (err) {
reject(err)
}
});
}
OR (what I think I would've tried)
function verifyToken(token: string): Promise<ABetterType> {
return new Promise((resolve, reject) => {
try {
const decoded = jwt.verify(token, this._publicKey);
resolve(decoded);
} catch (err) {
reject(err);
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With