Skip to content

Bug: makeHandlerIdempotent error handler throws "Cannot read properties of undefined" #4634

@mdesousa

Description

@mdesousa

Expected Behavior

The middy handler makeHandlerIdempotent should handle errors without throwing

Current Behavior

The handler throws Cannot read properties of undefined (reading 'handleMiddyOnError') during error handling, when the following is true:

  • there is middleware A that executes before powertools makeHandlerIdempotent
  • while processing a request, middleware A throws an error. this happens before makeHandlerIdempotent.before() has executed
  • middy invokes the onError handler for all middlewares, even the ones that did not initialize. this diagram shows the flow for error handling. not in the error example "3rd middleware" didn't execute the before() step, but its onError() is still invoked.
  • makeHandlerIdempotent throws if onError() is executed when before() has not.

Code snippet

import middy from '@middy/core'
import middleware1 from 'sample-middleware1'
import middleware2 from 'sample-middleware2'
import { makeHandlerIdempotent } from '@aws-lambda-powertools/idempotency/middleware';

const lambdaHandler = (event, context) => {
  /* your business logic */
}

export const handler = middy()
  .use(middleware1())
  .use(middleware2())
  .use(makeHandlerIdempotent())
  .handler(lambdaHandler)

Steps to Reproduce

  1. configure a middy handler as shown above
  2. execute a request where middeware1 or middleware2 throw an error in the before() step
  3. makeHandlerIdempotent() throws: Cannot read properties of undefined (reading 'handleMiddyOnError')

Possible Solution

See the snippet below from packages/idempotency/src/middleware/makeHandlerIdempotent.ts. The last line does not check if idempotencyHandler is undefined. just need to add validation and return if it hasn't.

  const onError = async (request: MiddyLikeRequest): Promise<void> => {
    if (shouldSkipIdempotency(request)) {
      return;
    }
    const idempotencyHandler =
      getIdempotencyHandlerFromRequestInternal(request);
    await idempotencyHandler.handleMiddyOnError();
  };

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

22.x

Packaging format used

npm

Execution logs

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingconfirmedThe scope is clear, ready for implementation

Type

No type

Projects

Status

Coming soon

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions