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:
- Why does the catch not solve this problem?
- Is there any better solution to avoid an unhandled error in promisses inside an async function?