Skip to content

feat(event-handler): add support for error handling in AppSync GraphQL #4317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 33 commits into
base: main
Choose a base branch
from

Conversation

arnabrahman
Copy link
Contributor

@arnabrahman arnabrahman commented Aug 13, 2025

Summary

This PR adds support for error handling in AppSync GraphQL described in the issue

Changes

  • exceptionHandler method is introduced to register an exception and its handler.
  • ExceptionHandlerRegistry is introduced to keep track of registered exception handlers
  • exceptionHandler is also exposed as a decorator method
  • Unit tests are written for 100% coverage
  • Added documentation for exception handling with examples
  • Minor housekeeping(ex: dockerfile nodejs version update due to error & endregion added)

Lambda handler:

import { AppSyncGraphQLResolver } from '@aws-lambda-powertools/event-handler/appsync-graphql';
import { Logger } from '@aws-lambda-powertools/logger';
import { AssertionError } from 'assert';
import type { Context } from 'aws-lambda';

const logger = new Logger({
  serviceName: 'MyService',
});
const app = new AppSyncGraphQLResolver({ logger });

app.exceptionHandler(AssertionError, async (error) => {
  return {
    error: {
      message: error.message,
      type: error.name,
    },
  };
});

app.onQuery('createSomething', async () => {
  throw new AssertionError({
    message: 'This is an assertion Error',
  });
});

export const handler = async (event: unknown, context: Context) =>
  app.resolve(event, context);

Response mapping template

#if (!$util.isNull($ctx.result.error))
  $util.error($ctx.result.error.message, $ctx.result.error.type)
#end

$utils.toJson($ctx.result)

Response:

{
  "data": {
    "createSomething": null
  },
  "errors": [
    {
      "path": [
        "createSomething"
      ],
      "data": null,
      "errorType": "AssertionError",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "This is an assertion Error"
    }
  ]
}

Issue number: closes #4130


By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

@pull-request-size pull-request-size bot added the size/XL PRs between 500-999 LOC, often PRs that grown with feedback label Aug 13, 2025
@boring-cyborg boring-cyborg bot added documentation Improvements or additions to documentation event-handler This item relates to the Event Handler Utility tests PRs that add or change tests labels Aug 13, 2025
Copy link

@arnabrahman
Copy link
Contributor Author

arnabrahman commented Aug 13, 2025

I have one observation: while looking into the Python documentation, I realized they also accept list of errors for exception handling. Should we support that as well?

@arnabrahman arnabrahman marked this pull request as ready for review August 13, 2025 04:52
@svozza
Copy link
Contributor

svozza commented Aug 13, 2025

I have one observation: while looking into the Python documentation, I realized they also accept list of errors for exception handling. Should we support that as well?

Yes, that's what I'm doing in the API Gateway event handler so we should be consistent:

@@ -2,7 +2,7 @@
FROM squidfunk/mkdocs-material@sha256:bb7b015690d9fb5ef0dbc98ca3520f153aa43129fb96aec5ca54c9154dc3b729

# Install Node.js
RUN apk add --no-cache nodejs=22.13.1-r0 npm
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this intentional?

Copy link
Contributor Author

@arnabrahman arnabrahman Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, as other version is failing in my local


You can use the **`exceptionHandler`** method with any exception. This allows you to handle common errors outside your resolver and return a custom response.

You can use a VTL response mapping template to detect these custom responses and forward them to the client gracefully.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The recommended way to do response mapping is JS now, not VTL, so we should include an example of how to do it that way.

}

this.#logger.debug(`No exception handler found for error: ${errorName}`);
return undefined;
Copy link
Contributor

@svozza svozza Aug 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We return null in the API Gateway handler so let's do the same here.

context
);

// Assess
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test should have have an assertion somewhere to ensure that the this context is being preserved.

/**
* Checks if there are any registered exception handlers.
*/
public hasHandlers(): boolean {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this function? I think it's sufficient for the client to call resolve and check whether it returns null or not.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that can also be done too

@arnabrahman arnabrahman marked this pull request as draft August 13, 2025 13:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation event-handler This item relates to the Event Handler Utility size/XL PRs between 500-999 LOC, often PRs that grown with feedback tests PRs that add or change tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feature request: support error handling in AppSync GraphQL
2 participants