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

Open
wants to merge 37 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 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
9366f86
feat: PR feedback resolved
arnabrahman Aug 21, 2025
10adbb9
fix: enhance exception handling documentation and add example resolver
arnabrahman Aug 21, 2025
ddb217b
fix: revert Node.js version to 22.13.1 in Dockerfile
arnabrahman Aug 21, 2025
be3dc59
fix: sonarqube issue resolved
arnabrahman Aug 21, 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
32 changes: 32 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,38 @@ 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 to handle any exception. This allows you to handle common errors outside your resolver and return a custom response.

The **`exceptionHandler`** method also supports passing an array of exceptions that you wish to handle with a single handler.

You can use an AppSync JavaScript resolver or a VTL response mapping template to detect these custom responses and forward them to the client gracefully.

=== "Exception Handling"

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

=== "APPSYNC JS Resolver"

```js hl_lines="11-13"
--8<-- "examples/snippets/event-handler/appsync-graphql/exceptionHandlingResolver.js"
```

=== "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,15 @@
import { util } from '@aws-appsync/utils';

export function request(ctx) {
return {
operation: 'Invoke',
payload: ctx,
};
}

export function response(ctx) {
if (ctx.result.error) {
return util.error(ctx.result.error.message, ctx.result.error.type);
}
return ctx.result;
}
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 @@ -166,7 +166,8 @@ class AppSyncGraphQLResolver extends Router {
}
return this.#withErrorHandling(
() => this.#executeBatchResolvers(event, context, options),
event[0]
event[0],
options
);
}
if (!isAppSyncGraphQLEvent(event)) {
Expand All @@ -178,7 +179,8 @@ class AppSyncGraphQLResolver extends Router {

return this.#withErrorHandling(
() => this.#executeSingleResolver(event, context, options),
event
event,
options
);
}

Expand All @@ -189,17 +191,20 @@ class AppSyncGraphQLResolver extends Router {
*
* @param fn - A function returning a Promise to be executed with error handling.
* @param event - The AppSync resolver event (single or first of batch).
* @param options - Optional resolve options for customizing resolver behavior.
*/
async #withErrorHandling(
fn: () => Promise<unknown>,
event: AppSyncResolverEvent<Record<string, unknown>>
event: AppSyncResolverEvent<Record<string, unknown>>,
options?: ResolveOptions
): Promise<unknown> {
try {
return await fn();
} catch (error) {
return this.#handleError(
return await this.#handleError(
error,
`An error occurred in handler ${event.info.fieldName}`
`An error occurred in handler ${event.info.fieldName}`,
options
);
}
}
Expand All @@ -209,16 +214,39 @@ 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.
* @param options - Optional resolve options for customizing resolver behavior.
* @throws InvalidBatchResponseException | ResolverNotFoundException
*/
#handleError(error: unknown, errorMessage: string) {
async #handleError(
error: unknown,
errorMessage: string,
options?: ResolveOptions
): Promise<unknown> {
this.logger.error(errorMessage, error);
if (error instanceof InvalidBatchResponseException) throw error;
if (error instanceof ResolverNotFoundException) throw error;
if (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.apply(options?.scope ?? this, [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,93 @@
import type { GenericLogger } from '@aws-lambda-powertools/commons/types';
import type {
ErrorClass,
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 one or more error classes.
*
* 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(es) and their associated handler.
* @param options.error - A single error class or an array of error classes to handle.
* @param options.handler - The exception handler function that will be invoked when the error occurs.
*/
public register(options: ExceptionHandlerOptions<Error>): void {
const { error, handler } = options;
const errors = Array.isArray(error) ? error : [error];

for (const err of errors) {
this.registerErrorHandler(err, handler as ExceptionHandler);
}
}

/**
* Registers a error handler for a specific error class.
*
* @param errorClass - The error class to register the handler for.
* @param handler - The exception handler function.
*/
private registerErrorHandler(
errorClass: ErrorClass<Error>,
handler: ExceptionHandler
): void {
const errorName = errorClass.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: errorClass,
handler,
});
}

/**
* 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, `null` is returned.
*
* @param error - The error instance for which to resolve an exception handler.
*/
public resolve(error: Error): ExceptionHandler | null {
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 null;
}
}

export { ExceptionHandlerRegistry };
Loading
Loading