diff --git a/docs/constructs/interfaces/GraphQlApiProps.html b/docs/constructs/interfaces/GraphQlApiProps.html index 18a59ae..1c7d9e6 100644 --- a/docs/constructs/interfaces/GraphQlApiProps.html +++ b/docs/constructs/interfaces/GraphQlApiProps.html @@ -168,10 +168,14 @@
OptionalIf true, addLambdaResolver synthesizes an APPSYNC_JS pipeline resolver whose
response handler converts the errors.appsync.* envelope returned by
createAppSyncHandler into a typed GraphQL error.
+Untyped errors still fail the invocation, and the pipeline function raises
+them as GraphQL errors with AppSync's invoke error type (e.g.
+Lambda:Unhandled), as a UNIT direct-Lambda resolver does.
When false (the default), addLambdaResolver synthesizes a plain UNIT
-direct-Lambda resolver (the pre-#385 behavior) with no response handler. On
-that path, if a handler throws an AppSyncError the sentinel envelope is
-returned as field data instead of becoming a GraphQL error.
+direct-Lambda resolver (the pre-#385 behavior) with no response handler.
+The Lambda gets no APPSYNC_TYPED_ERRORS flag, so createAppSyncHandler
+rethrows an AppSyncError and AppSync reports it as Lambda:Unhandled
+without the typed errorType and errorInfo.
This flag applies to ALL Lambda resolvers on the API. Enabling it changes
the resolver topology from UNIT to PIPELINE, which produces a cdk diff for
every Lambda resolver, so opt in deliberately.
diff --git a/llm.md b/llm.md
index 3847b34..83a0a36 100644
--- a/llm.md
+++ b/llm.md
@@ -210,7 +210,7 @@ export const handler = createAppSyncHandler(async (ctx) => {
HTTP errors from the shared authorizer are translated the same way. The shared `JwtAuthorizer` base throws `errors.UnauthenticatedError` (401) and `errors.ForbiddenError` (403) from `assertAuthenticated`/`assertGroup`/`assertAdmin`, and `AppSyncCognitoAuthorizer` extends that base, so these reach `createAppSyncHandler`'s catch. `createAppSyncHandler` treats any `errors.HttpError` like a typed error and maps its `statusCode` to an `errorType`: 400 `BadRequest`, 401 `Unauthorized`, 403 `Forbidden`, 404 `NotFound`, any other status `Error`. The mapped error goes through the same `APPSYNC_TYPED_ERRORS` gate and `{ __appSyncError: true, ... }` envelope as `errors.appsync.*` (with `errorInfo` undefined, since `HttpError` carries none). `src/lambda/auth.ts` and the HTTP handler `createHttpHandler` are unchanged. The same rethrow-when-not-activated rule applies, so a default UNIT resolver whose handler hits an auth assertion still fails loudly unless `typedErrors` is active.
-The envelope only becomes a GraphQL error when the resolver is wired via `GraphQlApi.addLambdaResolver` and the API opts in with `typedErrors: true`. On that path the method creates an `APPSYNC_JS` pipeline resolver whose response handler reads the envelope and calls `util.error(errorMessage, errorType, null, errorInfo)` (and `util.appendError` for invoke-level errors), turning the typed error into a GraphQL error with the matching `errorType` and `errorInfo`. Without `typedErrors: true`, `addLambdaResolver` creates a plain direct-Lambda UNIT resolver with no response handler, so the envelope is surfaced as the field's data instead. If you build the resolver yourself, replicate that response handler.
+The envelope only becomes a GraphQL error when the resolver is wired via `GraphQlApi.addLambdaResolver` and the API opts in with `typedErrors: true`. On that path the method creates an `APPSYNC_JS` pipeline resolver whose response handler reads the envelope and calls `util.error(errorMessage, errorType, null, errorInfo)`, turning the typed error into a GraphQL error with the matching `errorType` and `errorInfo`. Invoke-level errors (an untyped error the handler rethrows, a timeout) are raised by the pipeline function's own response handler with `util.error(ctx.error.message, ctx.error.type)`, because AppSync drops an error left in a pipeline function's `ctx.error` and the field would resolve to `null` with no GraphQL error. Without `typedErrors: true`, `addLambdaResolver` creates a plain direct-Lambda UNIT resolver with no response handler and sets no `APPSYNC_TYPED_ERRORS` flag, so typed errors rethrow and surface as `Lambda:Unhandled`. If you build the pipeline yourself, replicate both response handlers.
The response handler recognises the envelope by a reserved `__appSyncError` sentinel key that `createAppSyncHandler` stamps, not by the presence of an `errorMessage` field. A resolver whose real return type happens to include an `errorMessage` field is therefore passed through unchanged.
diff --git a/src/constructs/graphql.ts b/src/constructs/graphql.ts
index df9dd5c..a414e67 100644
--- a/src/constructs/graphql.ts
+++ b/src/constructs/graphql.ts
@@ -36,10 +36,15 @@ export interface GraphQlApiProps extends BaseApiProps {
* response handler converts the errors.appsync.* envelope returned by
* createAppSyncHandler into a typed GraphQL error.
*
+ * Untyped errors still fail the invocation, and the pipeline function raises
+ * them as GraphQL errors with AppSync's invoke error type (e.g.
+ * `Lambda:Unhandled`), as a UNIT direct-Lambda resolver does.
+ *
* When false (the default), addLambdaResolver synthesizes a plain UNIT
- * direct-Lambda resolver (the pre-#385 behavior) with no response handler. On
- * that path, if a handler throws an AppSyncError the sentinel envelope is
- * returned as field data instead of becoming a GraphQL error.
+ * direct-Lambda resolver (the pre-#385 behavior) with no response handler.
+ * The Lambda gets no APPSYNC_TYPED_ERRORS flag, so createAppSyncHandler
+ * rethrows an AppSyncError and AppSync reports it as `Lambda:Unhandled`
+ * without the typed errorType and errorInfo.
*
* This flag applies to ALL Lambda resolvers on the API. Enabling it changes
* the resolver topology from UNIT to PIPELINE, which produces a cdk diff for
@@ -447,9 +452,16 @@ export function request(ctx) {
};
}
-// Pass the Lambda result through unchanged; the resolver response handler
-// converts the error envelope into a GraphQL error.
+// A failed invoke (an untyped error rethrown by createAppSyncHandler, a timeout,
+// a missing permission) lands in this function's ctx.error. AppSync drops it
+// unless this handler raises it, and the field would resolve to null with no
+// GraphQL error. Raise it with the same message and type a UNIT direct-Lambda
+// resolver reports. Otherwise pass the result through; the resolver response
+// handler converts the typed error envelope into a GraphQL error.
export function response(ctx) {
+ if (ctx.error) {
+ util.error(ctx.error.message, ctx.error.type);
+ }
return ctx.result;
}
`),
@@ -476,11 +488,10 @@ export function request(ctx) {
// createAppSyncHandler stamps. Branching on the sentinel (not on a bare
// errorMessage) means a legitimate result that merely has an errorMessage field
// is returned unchanged instead of being misread as a typed error.
+//
+// Invoke-level errors are raised by the pipeline function itself: an error left
+// in a function's ctx.error never reaches this handler's ctx.error.
export function response(ctx) {
- if (ctx.error) {
- util.appendError(ctx.error.message, ctx.error.type, ctx.result);
- return ctx.result;
- }
const result = ctx.prev.result;
if (result && result.__appSyncError) {
util.error(result.errorMessage, result.errorType, null, result.errorInfo);
diff --git a/test/constructs/graphql.test.ts b/test/constructs/graphql.test.ts
index bd746f9..dbb66fc 100644
--- a/test/constructs/graphql.test.ts
+++ b/test/constructs/graphql.test.ts
@@ -237,19 +237,15 @@ type Post {
Code: Match.stringLikeRegexp('return result;'),
});
- // The response handler also appends invoke-level errors.
- template.hasResourceProperties('AWS::AppSync::Resolver', {
- TypeName: 'Query',
- FieldName: 'getUser',
- Code: Match.stringLikeRegexp('util\\.appendError\\(ctx\\.error\\.message, ctx\\.error\\.type, ctx\\.result\\)'),
- });
-
- // The Lambda invoke runs as an APPSYNC_JS pipeline function.
+ // The Lambda invoke runs as an APPSYNC_JS pipeline function, which raises
+ // invoke-level errors itself: AppSync drops an error left in a pipeline
+ // function's ctx.error, so the resolver handler could never see it.
template.hasResourceProperties('AWS::AppSync::FunctionConfiguration', {
Runtime: {
Name: 'APPSYNC_JS',
RuntimeVersion: '1.0.0',
},
+ Code: Match.stringLikeRegexp('util\\.error\\(ctx\\.error\\.message, ctx\\.error\\.type\\)'),
});
// Verify Lambda function is created
@@ -272,6 +268,90 @@ type Post {
template.resourceCountIs('AWS::CloudFormation::Stack', 0);
});
+ describe('typedErrors handler behavior', () => {
+ /**
+ * Loads an inline APPSYNC_JS module with a fake `util` whose error() throws
+ * like the AppSync runtime does, so the handlers can be exercised in Jest.
+ */
+ const loadHandlers = (code: string, util: any): { request: Function; response: Function } => {
+ const body = code
+ .replace(/^import .*$/m, '')
+ .replace(/export function/g, 'function');
+ return new Function('util', `${body}\nreturn { request, response };`)(util);
+ };
+
+ class FakeAppSyncError extends Error {
+ constructor(message: string, public readonly errorType?: string, public readonly errorInfo?: unknown) {
+ super(message);
+ }
+ }
+ const fakeUtil = {
+ error: (message: string, errorType?: string, _data?: unknown, errorInfo?: unknown) => {
+ throw new FakeAppSyncError(message, errorType, errorInfo);
+ },
+ };
+
+ let functionResponse: Function;
+ let resolverResponse: Function;
+
+ beforeEach(() => {
+ const api = new GraphQlApi(stack, 'TestApi', {
+ apiName: 'TestAPI',
+ stageName: 'test',
+ definitionFileName: schemaPath,
+ authentication,
+ typedErrors: true,
+ });
+ api.addLambdaResolver('Query', 'getUser');
+ const template = Template.fromStack(stack);
+
+ const [fnConfig] = Object.values(template.findResources('AWS::AppSync::FunctionConfiguration'));
+ const [resolver] = Object.values(template.findResources('AWS::AppSync::Resolver'));
+ functionResponse = loadHandlers(fnConfig.Properties.Code, fakeUtil).response;
+ resolverResponse = loadHandlers(resolver.Properties.Code, fakeUtil).response;
+ });
+
+ test('pipeline function raises an invoke error instead of resolving to null', () => {
+ // What AppSync hands the function when the handler rethrows an untyped error.
+ const ctx = {
+ result: null,
+ error: { message: 'Team "X" not found', type: 'Lambda:Unhandled' },
+ };
+
+ expect(() => functionResponse(ctx)).toThrow(
+ expect.objectContaining({ message: 'Team "X" not found', errorType: 'Lambda:Unhandled' }),
+ );
+ });
+
+ test('pipeline function passes a successful result through', () => {
+ const result = { id: '1' };
+ expect(functionResponse({ result })).toBe(result);
+ });
+
+ test('resolver raises the typed error envelope with errorType and errorInfo', () => {
+ const ctx = {
+ prev: {
+ result: {
+ __appSyncError: true,
+ data: null,
+ errorType: 'NotFound',
+ errorMessage: 'User not found',
+ errorInfo: { id: '1' },
+ },
+ },
+ };
+
+ expect(() => resolverResponse(ctx)).toThrow(
+ expect.objectContaining({ message: 'User not found', errorType: 'NotFound', errorInfo: { id: '1' } }),
+ );
+ });
+
+ test('resolver passes a result without the sentinel through', () => {
+ const result = { id: '1', errorMessage: 'a legitimate field' };
+ expect(resolverResponse({ prev: { result } })).toBe(result);
+ });
+ });
+
test('creates multiple resolvers in the main stack', () => {
const api = new GraphQlApi(stack, 'TestApi', {
apiName: 'TestAPI',