Node-jsonwebtoken: JsonWebTokenError extends Error class

Created on 10 Oct 2017  路  2Comments  路  Source: auth0/node-jsonwebtoken

I'm writing a REST API with JWT authorization, and only want to know, why did you guys don't make JsonWebTokenError function on /lib/JsonWebTokenError.js a class that extends Error class ?
I though that for better 'checking' (maybe not the words), when handling errors with try/catch.

So instead

try{      
 // with the JsonWebTokenError here     
} catch (err) {     
if (err.message === 'jwt malformed') {     
// and handle this..      
}      

becomes this:

try{  
 // with the JsonWebTokenError here  
} catch (err) {  
if (err instanceof JsonWebTokenError) {  
// and handle this..   
}  

or even more specific like:

/ ...   
if (err instanceof MalformedJsonWebToken)  
/ ...     

Thanks in advance :smile:

Most helpful comment

We do not "extend Error class" but we use Object.create() to achieve the inheritance.

Isn't working for you? You can find the errors in the root of the library:

const jwt = require('jsonwebtoken');
jwt.JsonWebTokenError

To let you do if (err instanceof jwt.JsonWebTokenError) {}

All 2 comments

We do not "extend Error class" but we use Object.create() to achieve the inheritance.

Isn't working for you? You can find the errors in the root of the library:

const jwt = require('jsonwebtoken');
jwt.JsonWebTokenError

To let you do if (err instanceof jwt.JsonWebTokenError) {}

@ziluvatar Thank you man! I wrote this in the "fire" of a sprint, only to know! Thank you for the tip! :+1: :smile: You guys are awesome!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

svnty picture svnty  路  3Comments

AndreOneti picture AndreOneti  路  3Comments

shea256 picture shea256  路  3Comments

ngminhduong picture ngminhduong  路  3Comments

cope picture cope  路  4Comments