mikenicholson / passport-jwt

Passport authentication using JSON Web Tokens
MIT License
1.97k stars 214 forks source link

Throw a named error instead of a generic error, when no auth token is provided #222

Open abdatta opened 4 years ago

abdatta commented 4 years ago

Hi, I have a requirement where I want to catch only the No auth token errors on authentication failure. Right now I have to check exactly the message property like this: err.message === 'No auth token'. However, I'm afraid any future change in the error message might break my app.

https://github.com/mikenicholson/passport-jwt/blob/96a6e5565ba5a6f3301d91959a0f646e54446388/lib/strategy.js#L96

So I request to define an error class for it like this:

class NoAuthTokenError extends Error {
    message = 'No auth token';
}

and then throw that instead

return self.fail(new NoAuthTokenError()); 

This helps me to check the error using: err instanceof NoAuthTokenError, and any future change to the error message won't cause any breaking change.

Lemme know if this sounds reasonable. I'll create a PR for the same then.

Outternet commented 2 years ago

This is a good point, either error classes (wich is against the offical passport documentation) or error messages should be put in an enum. Please add a PR (if you can directly to the rewrite)