Issue
I'd like to check whether the type of an Error
is TokenExpiredError
throws by the jwt.verify
function of the jsonwebtoken
library using Typescript's instanceof
, e.g.
import jwt from "jsonwebtoken";
function someFunction() {
try {
return jwt.verify(token, key);
}catch(err) {
if(err instanceof TokenExpiredError) {
return attemptRenewal()
}
throw err
}
}
How can I import the symbol TokenExpiredError
?
I don't find any documentation about this important class and the only intuitive that comes to my mind
import { jwt, TokenExpiredError } from "jsonwebtoken";
causes jwt
to be undefined
.
I'm aware of workaround like performing string comparison with the class name, but I'd like to produce clean code.
I'm using jsonwebtoken
8.5.1.
Solution
jsonwebtoken
export a default object like: source
module.exports = {
decode: require('./decode'),
verify: require('./verify'),
sign: require('./sign'),
JsonWebTokenError: require('./lib/JsonWebTokenError'),
NotBeforeError: require('./lib/NotBeforeError'),
TokenExpiredError: require('./lib/TokenExpiredError'),
};
This mean, when you use import jwt from "jsonwebtoken";
syntax, jwt
will come to a object with all properties of default export.
You can not use import { jwt, TokenExpiredError } from "jsonwebtoken";
, because in default export object, we do not have jwt
property,
If you want to import TokenExpiredError
and the default object, you can follow a syntax like: import jwt, {TokenExpiredError} from "jsonwebtoken";
, then jwt
still is default export object, and you have TokenExpiredError
object (jwt.TokenExpiredError
and TokenExpiredError
is the same).
If you just want to use verify
function and TokenExpiredError
, the import line will come to: import {TokenExpiredError, verify} from "jsonwebtoken";
, then you function will be like:
import {TokenExpiredError, verify} from "jsonwebtoken";
function someFunction() {
try {
return verify(token, key);
} catch (err) {
if (err instanceof TokenExpiredError) {
return attemptRenewal()
}
throw err
}
}
Answered By - hoangdv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.