From f436ae45e5f52add12af8ea4f9748f56ce0b9404 Mon Sep 17 00:00:00 2001 From: JAPER Date: Tue, 2 Sep 2025 09:57:05 +1000 Subject: [PATCH] Handle errors from context functions --- README.md | 2 ++ collectInvocation.js | 11 ++++++++++- tests/collectInvocation.test.js | 16 ++++++++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9d57683..5aa128c 100644 --- a/README.md +++ b/README.md @@ -198,3 +198,5 @@ aws lambda invoke \ ## Debugging Set `DEBUG=1` (or any non-empty value) to enable additional log output. This can help troubleshoot event dispatching and handler execution. + +When invocation data is collected, functions on the `context` object are invoked. If a context function throws an error, its message is captured and included in the logged context instead of halting execution. diff --git a/collectInvocation.js b/collectInvocation.js index 4021fa2..4a11b0a 100644 --- a/collectInvocation.js +++ b/collectInvocation.js @@ -3,6 +3,7 @@ * * The raw `context` object exposes functions, so we copy its enumerable * properties while invoking any functions to capture their returned values. + * If a function throws, its error message is stored instead of aborting. * This keeps test snapshots stable and avoids leaking functions. * * @param {object} event - Event payload provided to the Lambda. @@ -14,7 +15,15 @@ export default function collectInvocation(event, context, handlerType) { const ctx = {}; if (context) { for (const [key, value] of Object.entries(context)) { - ctx[key] = typeof value === 'function' ? value.call(context) : value; + if (typeof value === 'function') { + try { + ctx[key] = value.call(context); + } catch (err) { + ctx[key] = err && err.message ? err.message : String(err); + } + } else { + ctx[key] = value; + } } } return { event, context: ctx, handlerType }; diff --git a/tests/collectInvocation.test.js b/tests/collectInvocation.test.js index 4f7f8af..f4bc29c 100644 --- a/tests/collectInvocation.test.js +++ b/tests/collectInvocation.test.js @@ -21,4 +21,20 @@ describe('collectInvocation', () => { handlerType: 'test' }); }); + + test('handles context functions that throw', () => { + const event = {}; + const context = { + ok: () => 'good', + fail() { throw new Error('boom'); } + }; + + const result = collectInvocation(event, context, 'test'); + + expect(result).toEqual({ + event, + context: { ok: 'good', fail: 'boom' }, + handlerType: 'test' + }); + }); });