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
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
9f97957
feat: add types for exception handling in event handler
arnabrahman Aug 3, 2025
b588562
refactor: improve exception handling types for better type safety
arnabrahman Aug 4, 2025
c36c93c
feat: implement ExceptionHandlerRegistry for managing GraphQL excepti…
arnabrahman Aug 4, 2025
150157e
feat: add exception handling support in AppSyncGraphQLResolver and Ro…
arnabrahman Aug 4, 2025
432f5d6
test: add unit tests for ExceptionHandlerRegistry functionality
arnabrahman Aug 4, 2025
081e805
feat: add exception handling for ValidationError, NotFoundError, and …
arnabrahman Aug 6, 2025
b7a2846
fix: correct import path for ExceptionHandlerRegistry in unit tests
arnabrahman Aug 6, 2025
d1a499d
fix: update import path for Router in unit tests
arnabrahman Aug 6, 2025
2e1b853
fix: update exceptionHandler method signature for improved type handling
arnabrahman Aug 6, 2025
3dc04b6
fix: update AssertionError usage in examples for consistency
arnabrahman Aug 6, 2025
5df6159
feat: enhance exception handling by registering handlers for multiple…
arnabrahman Aug 8, 2025
32919da
fix: update error message formatting in exception handler for clarity
arnabrahman Aug 8, 2025
d024aad
fix: update NotFoundError handling to use '0' as the identifier for n…
arnabrahman Aug 8, 2025
66ff42e
fix: improve error handling in exception handler test for ValidationE…
arnabrahman Aug 8, 2025
aac7f9f
fix: update exception handler test to use synchronous handling for Va…
arnabrahman Aug 8, 2025
ad1793e
fix: update test descriptions to clarify exception handling behavior …
arnabrahman Aug 8, 2025
737248d
fix: improve test descriptions for clarity in AppSyncGraphQLResolver
arnabrahman Aug 8, 2025
e93530c
fix: update error formatting to use constructor name in AppSyncGraphQ…
arnabrahman Aug 10, 2025
737a766
fix: simplify error throwing logic in onQuery handler for better read…
arnabrahman Aug 10, 2025
b4d307c
fix: update error handling to use error name instead of constructor n…
arnabrahman Aug 10, 2025
22433a6
doc: update documentation to clarify that exception handler resolutio…
arnabrahman Aug 10, 2025
eb049cf
doc: add missing region end comments for better code organization
arnabrahman Aug 10, 2025
47c6c6a
test: add console error expectation for ValidationError in getUser ha…
arnabrahman Aug 10, 2025
3a7d8dc
fix: update sync validation error message for clarity
arnabrahman Aug 10, 2025
69ed880
feat: enhance error handling in AppSyncGraphQLResolver with NotFoundE…
arnabrahman Aug 10, 2025
e51c43b
fix: correct handler variable usage in ExceptionHandlerRegistry tests
arnabrahman Aug 10, 2025
e018758
doc: exception handling support in appsync-graphql
arnabrahman Aug 12, 2025
fb08824
fix: update exception handler logging to use error name for clarity
arnabrahman Aug 12, 2025
433f10a
fix: improve error handling for AssertionError with detailed error st…
arnabrahman Aug 12, 2025
4952c79
fix: update parameter name in exceptionHandler for clarity
arnabrahman Aug 12, 2025
85b5c8c
fix: enhance exception handling documentation and response structure
arnabrahman Aug 13, 2025
5aaac53
fix: clarify documentation for exception handler options and resolver…
arnabrahman Aug 13, 2025
c79f5bc
test: enhance test descriptions for clarity in exception handling sce…
arnabrahman Aug 13, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Contributor

Choose a reason for hiding this comment

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

I remember you modified this in a previous PR and had to revert it back - I am unsure what's happening here, but I'd say let's not include it as part of this PR.

If you need this to get the docs running locally for now keep the change in your local branch if possible.

RUN apk add --no-cache nodejs=22.15.1-r0 npm

COPY requirements.txt /tmp/
RUN pip install --require-hashes -r /tmp/requirements.txt
24 changes: 24 additions & 0 deletions docs/features/event-handler/appsync-graphql.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,30 @@ You can access the original Lambda event or context for additional information.

1. The `event` parameter contains the original AppSync event and has type `AppSyncResolverEvent` from the `@types/aws-lambda`.

### Exception Handling

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.


=== "Exception Handling"

```typescript hl_lines="11-18 21-23"
--8<-- "examples/snippets/event-handler/appsync-graphql/exceptionHandling.ts"
```

=== "VTL Response Mapping Template"

```velocity hl_lines="1-3"
--8<-- "examples/snippets/event-handler/appsync-graphql/exceptionHandlingResponseMapping.vtl"
```

=== "Exception Handling response"

```json hl_lines="11 20"
--8<-- "examples/snippets/event-handler/appsync-graphql/exceptionHandlingResponse.json"
```

### Logging

By default, the utility uses the global `console` logger and emits only warnings and errors.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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);
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"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"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#if (!$util.isNull($ctx.result.error))
$util.error($ctx.result.error.message, $ctx.result.error.type)
#end

$utils.toJson($ctx.result)
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ class AppSyncGraphQLResolver extends Router {
try {
return await fn();
} catch (error) {
return this.#handleError(
return await this.#handleError(
error,
`An error occurred in handler ${event.info.fieldName}`
);
Expand All @@ -209,16 +209,34 @@ class AppSyncGraphQLResolver extends Router {
*
* Logs the provided error message and error object. If the error is an instance of
* `InvalidBatchResponseException` or `ResolverNotFoundException`, it is re-thrown.
* Checks for registered exception handlers and calls them if available.
* Otherwise, the error is formatted into a response using `#formatErrorResponse`.
*
* @param error - The error object to handle.
* @param errorMessage - A descriptive message to log alongside the error.
* @throws InvalidBatchResponseException | ResolverNotFoundException
*/
#handleError(error: unknown, errorMessage: string) {
async #handleError(error: unknown, errorMessage: string): Promise<unknown> {
this.logger.error(errorMessage, error);
if (error instanceof InvalidBatchResponseException) throw error;
if (error instanceof ResolverNotFoundException) throw error;
if (this.exceptionHandlerRegistry.hasHandlers() && error instanceof Error) {
const exceptionHandler = this.exceptionHandlerRegistry.resolve(error);
if (exceptionHandler) {
try {
this.logger.debug(
`Calling exception handler for error: ${error.name}`
);
return await exceptionHandler(error);
} catch (handlerError) {
this.logger.error(
`Exception handler for ${error.name} threw an error`,
handlerError
);
}
}
}

return this.#formatErrorResponse(error);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { GenericLogger } from '@aws-lambda-powertools/commons/types';
import type {
ExceptionHandler,
ExceptionHandlerOptions,
ExceptionHandlerRegistryOptions,
} from '../types/appsync-graphql.js';

/**
* Registry for storing exception handlers for GraphQL resolvers in AWS AppSync GraphQL API's.
*/
class ExceptionHandlerRegistry {
/**
* A map of registered exception handlers, keyed by their error class name.
*/
protected readonly handlers: Map<string, ExceptionHandlerOptions> = new Map();
/**
* A logger instance to be used for logging debug and warning messages.
*/
readonly #logger: Pick<GenericLogger, 'debug' | 'warn' | 'error'>;

public constructor(options: ExceptionHandlerRegistryOptions) {
this.#logger = options.logger;
}

/**
* Registers an exception handler for a specific error class.
*
* If a handler for the given error class is already registered, it will be replaced and a warning will be logged.
*
* @param options - The options containing the error class and its associated handler.
*/
public register(options: ExceptionHandlerOptions<Error>): void {
const { error, handler } = options;
const errorName = error.name;

this.#logger.debug(`Adding exception handler for error class ${errorName}`);

if (this.handlers.has(errorName)) {
this.#logger.warn(
`An exception handler for error class '${errorName}' is already registered. The previous handler will be replaced.`
);
}

this.handlers.set(errorName, {
error,
handler: handler as ExceptionHandler,
});
}

/**
* Resolves and returns the appropriate exception handler for a given error instance.
*
* This method attempts to find a registered exception handler based on the error class name.
* If a matching handler is found, it is returned; otherwise, `undefined` is returned.
*
* @param error - The error instance for which to resolve an exception handler.
*/
public resolve(error: Error): ExceptionHandler | undefined {
const errorName = error.name;
this.#logger.debug(`Looking for exception handler for error: ${errorName}`);

const handlerOptions = this.handlers.get(errorName);
if (handlerOptions) {
this.#logger.debug(`Found exact match for error class: ${errorName}`);
return handlerOptions.handler;
}

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.

}

/**
* 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

return this.handlers.size > 0;
}
}

export { ExceptionHandlerRegistry };
114 changes: 114 additions & 0 deletions packages/event-handler/src/appsync-graphql/Router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import {
} from '@aws-lambda-powertools/commons/utils/env';
import type {
BatchResolverHandler,
ErrorClass,
ExceptionHandler,
GraphQlBatchRouteOptions,
GraphQlRouteOptions,
GraphQlRouterOptions,
ResolverHandler,
} from '../types/appsync-graphql.js';
import { ExceptionHandlerRegistry } from './ExceptionHandlerRegistry.js';
import { RouteHandlerRegistry } from './RouteHandlerRegistry.js';

/**
Expand All @@ -24,6 +27,10 @@ class Router {
* A map of registered routes for GraphQL batch events, keyed by their fieldNames.
*/
protected readonly batchResolverRegistry: RouteHandlerRegistry;
/**
* A map of registered exception handlers for handling errors in GraphQL resolvers.
*/
protected readonly exceptionHandlerRegistry: ExceptionHandlerRegistry;
/**
* A logger instance to be used for logging debug, warning, and error messages.
*
Expand Down Expand Up @@ -51,6 +58,9 @@ class Router {
this.batchResolverRegistry = new RouteHandlerRegistry({
logger: this.logger,
});
this.exceptionHandlerRegistry = new ExceptionHandlerRegistry({
logger: this.logger,
});
this.isDev = isDevMode();
}

Expand Down Expand Up @@ -946,6 +956,110 @@ class Router {
return descriptor;
};
}

/**
* Register an exception handler for a specific error class.
*
* Registers a handler for a specific error class that can be thrown by GraphQL resolvers.
* The handler will be invoked when an error of the specified class is thrown from any
* resolver function.
*
* @example
* ```ts
* import { AppSyncGraphQLResolver } from '@aws-lambda-powertools/event-handler/appsync-graphql';
* import { AssertionError } from 'assert';
*
* const app = new AppSyncGraphQLResolver();
*
* // Register an exception handler for AssertionError
* app.exceptionHandler(AssertionError, async (error) => {
* return {
* error: {
* message: error.message,
* type: error.name
* }
* };
* });
*
* // Register a resolver that might throw an AssertionError
* app.onQuery('createSomething', async () => {
* throw new AssertionError({
* message: 'This is an assertion Error',
* });
* });
*
* export const handler = async (event, context) =>
* app.resolve(event, context);
* ```
*
* As a decorator:
*
* @example
* ```ts
* import { AppSyncGraphQLResolver } from '@aws-lambda-powertools/event-handler/appsync-graphql';
* import { AssertionError } from 'assert';
*
* const app = new AppSyncGraphQLResolver();
*
* class Lambda {
* ⁣@app.exceptionHandler(AssertionError)
* async handleAssertionError(error: AssertionError) {
* return {
* error: {
* message: error.message,
* type: error.name
* }
* };
* }
*
* ⁣@app.onQuery('getUser')
* async getUser() {
* throw new AssertionError({
* message: 'This is an assertion Error',
* });
* }
*
* async handler(event, context) {
* return app.resolve(event, context, {
* scope: this, // bind decorated methods to the class instance
* });
* }
* }
*
* const lambda = new Lambda();
* export const handler = lambda.handler.bind(lambda);
* ```
*
* @param error - The error class to handle.
* @param handler - The handler function to be called when the error is caught.
*/
public exceptionHandler<T extends Error>(
error: ErrorClass<T>,
handler: ExceptionHandler<T>
): void;
public exceptionHandler<T extends Error>(
error: ErrorClass<T>
): MethodDecorator;
public exceptionHandler<T extends Error>(
error: ErrorClass<T>,
handler?: ExceptionHandler<T>
): MethodDecorator | undefined {
if (typeof handler === 'function') {
this.exceptionHandlerRegistry.register({
error,
handler: handler as ExceptionHandler<Error>,
});
return;
}

return (_target, _propertyKey, descriptor: PropertyDescriptor) => {
this.exceptionHandlerRegistry.register({
error,
handler: descriptor?.value,
});
return descriptor;
};
}
}

export { Router };
Loading
Loading