Skip to content

Commit 8ad0a6a

Browse files
flochazChazal
and
Chazal
authored
fix(metrics): publish metrics even if handler throw (#249)
* chore: Add workflows from projen * add lint for metrics * fix linting for logger * chore: Add failing test * fix: publish metrics on throw Co-authored-by: Chazal <[email protected]>
1 parent 71bb695 commit 8ad0a6a

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

packages/metrics/src/Metrics.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,12 @@ class Metrics implements MetricsInterface {
9393
this.functionName = context.functionName;
9494

9595
if (captureColdStartMetric) this.captureColdStart();
96-
const result = originalMethod?.apply(this, [event, context, callback]);
97-
this.purgeStoredMetrics();
98-
99-
return result;
96+
try {
97+
const result = originalMethod?.apply(this, [event, context, callback]);
98+
return result;
99+
} finally {
100+
this.purgeStoredMetrics();
101+
}
100102
};
101103
};
102104
}

packages/metrics/tests/unit/Metrics.test.ts

+25
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,31 @@ describe('Class: Metrics', () => {
428428
expect(loggedData[0]._aws.CloudWatchMetrics[0].Metrics.length).toBe(1);
429429
expect(loggedData[1]._aws.CloudWatchMetrics[0].Metrics.length).toBe(0);
430430
});
431+
432+
test('Using decorator should log even if exception thrown', async () => {
433+
const metrics = new Metrics({ namespace: 'test' });
434+
class LambdaFunction implements LambdaInterface {
435+
@metrics.logMetrics()
436+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
437+
// @ts-ignore
438+
public handler<TEvent, TResult>(
439+
_event: TEvent,
440+
_context: Context,
441+
_callback: Callback<TResult>,
442+
): void | Promise<TResult> {
443+
metrics.addMetric('test_name_1', MetricUnits.Count, 1);
444+
throw new Error('Test Error');
445+
}
446+
}
447+
448+
try {
449+
await new LambdaFunction().handler(dummyEvent, dummyContext, () => console.log('Lambda invoked!'));
450+
} catch (error) {
451+
// DO NOTHING
452+
}
453+
454+
expect(console.log).toBeCalledTimes(1);
455+
});
431456
});
432457

433458
describe('Feature: Custom Config Service', () => {

0 commit comments

Comments
 (0)