Using Koa v2.7.0 and TypeScript v3.3.1
My "errorHandler" middleware function being exported like this
export const clientErrorHandler = () => {
return async (ctx: Context, next: NextFunction) => {
try{
await next();
}
catch (err){
if(err instanceof HTTPClientError){
console.warn(err);
ctx.status = err.statusCode;
ctx.body = err.message;
ctx.app.emit('error', err, ctx);
}
}
}
}
My logic which handles the attachment of the middleware on the given Koa app looks like this:
export const handleErrors = (app: Koa) => {
const serverErrHandler = serverErrorHandler();
serverErrHandler._name = 'serverErrorHandler';
app.use(serverErrHandler)
}
The reason why I'm trying to create this property is due to this Koa documentation (see link below) which states that we can give middleware functions a _name property so that when we run the program with DEBUG=koa*
set, this middleware function will be able to have a name that shows up in the console.
Since JavaScript does not allow defining function names at runtime, you can also set a middleware's name as ._name. This is useful when you don't have control of a middleware's name. For example:
const path = require('path'); const serve = require('koa-static');
const publicFiles = serve(path.join(__dirname, 'public'));
publicFiles._name = 'static /public';
app.use(publicFiles);
Source of the above snippet: https://github.com/koajs/koa/blob/master/docs/guide.md#debugging-koa
However, when trying this, since I'm using TypeScript, it does not like it that I'm trying to set a property on this anonymous function.
[ts] Property '_name' does not exist on type '(ctx: Context, next: NextFunction) => Promise'.
I was hoping to determine the best way to go about enabling myself to be able to add this little _name
property to this anonymous function so that I could have solid debugging logs.