auth-header
auth-header copied to clipboard
Add and export InvalidHeaderError
This PR adds the InvalidHeaderError
which inherits from TypeError
. Throwing a custom error and exporting it allows a more precise error handling, since it's possible to know that the error was thrown by parse
. For example:
const { TokenExpiredError, verify } = require('jsonwebtoken');
const { InvalidHeaderError, parse } = require('auth-header');
const { UnauthorizedError } = require('src/errors');
const { userManager } = require('src/user');
function getUserByAuthorizationToken(header) {
try {
const { token } = parse(header);
verify(token);
return userManager.getUserByToken(token);
} catch (e) {
if (e instanceof InvalidHeaderError) {
throw new UnauthorizedError('Invalid header');
}
if (e instanceof TokenExpiredError) {
throw new UnauthorizedError('Expired token');
}
throw e;
}
}
So I replaced all TypeError
throws by InvalidHeaderError
on the parse
module and modified its tests accordingly, adding an assert for its message.
The InvalidHeaderError
implementation was based on the Custom Error Types section of the MDN Error documentation.
@izaakschroeder Any thoughts?
Thinking of maybe using https://www.npmjs.com/package/es6-error
Thanks for the contribution so far π Will look at this in more detail tonight after I get some rest.
@izaakschroeder If you're ok to add it as dependency that's awesome, just let me know.
BTW, any reason for babel-core being a dependency? Seems duplicated.
@izaakschroeder ping
Sorry for the delay, super busy as of late. Feel free to add the dependency π And babel-cli
should be a devDependency
for generating dist
, but that's it I think. If it's not like that, feel free to fix it up! π (Or I can get to it soonβ’)
@izaakschroeder Refactored in favour of es6-error and removed babel-core as dependency, please review.
@izaakschroeder ping
@izaakschroeder ping
@izaakschroeder ping?