Search code examples
node.jsmiddlewaremiddy

Extending a middy middleware function in nodejs


In my lambda code written in nodejs, I want to extend the httpErrorhandler middleware and create a wrapper around it.

Currently I have something like below.

module.exports.handler=middy(handle).use(httpErrorHandler(LoggingFactory.getLogger().log))

I want to create a customHttpErrorHandler which is nothing but just a wrapper outside httpErrorHandler.

module.exports.handler=middy(handle).use(customHttpErrorHandler(LoggingFactory.getLogger().log))

Is this possible? What do I need to put inside customHttpErrorHandler ? There is no additional functionality to be implemented. This new customHandler should just pass the control to standard httpErrorHandler.

customHttpErrorHandler might look something like below (pseudo code).

connectHttpErrorHandler = (logger) => httpErrorHandler(logger)

Solution

  • Hi core maintainer of Middy here. Your pseudo code is almost correct. In Middy >=2.0.0, httpErrorHandler takes an options object. See https://github.com/middyjs/middy/tree/main/packages/http-error-handler for documentation.

    const connectHttpErrorHandler = (logger) => httpErrorHandler({logger})
    
    const logger = LoggingFactory.getLogger().log
    
    module.exports.handler = middy(handler)
      .use(customHttpErrorHandler(logger))