I use Koa (2.11.0).
I have this very much simplified middleware function, which looks strange after simplification.
However, it is easier to ask the question. I have two if statements, and I throw three times. After throwing, I am unsure what would be the best thing to do in all three places:
- do nothing, Koa will handle all
- add return, while it makes no value adding it, at least some readability to the code.
- add return next()
//This is Koa middleware
const tokenProvider: (persons: string[]) => Middleware = (
): Middleware => {
return async (ctx: Context, next: () => Promise<void>): Promise<void> => {
const authorizationHeader: string = ctx.headers.authorization
if (!authorizationHeader) {
ctx.throw(STATUS_CODES.UNAUTHORIZED)
}
try {
const token: string = authorizationHeader.split(' ').pop()
if (!token ) {
ctx.throw(STATUS_CODES.FORBIDDEN)
// Should I use:
// - return
// - return next()
// - nothing should be used, as Koa will handle it
}
return next()
} catch (error) {
ctx.throw(STATUS_CODES.UNAUTHORIZED)
}
}
}
Koa's
ctx.throwactually throws an exception, so there's no point in putting statements immediately afterctx.throwas they will be skipped, just as they would withthrow new Error().This also means that this statement isn't useful:
Because you immediately catch it and turn it into something else after. This is how I would rewrite your middleware:
Note that I assume you're using
Bearertokens, but if you're using something else you can substitute this.