From c919728fb3992e042e95465591cc5ab8fe225964 Mon Sep 17 00:00:00 2001 From: Harvmaster Date: Fri, 7 Aug 2026 02:12:09 +0000 Subject: [PATCH] Handle errors in Predicate function --- source/event-emitter.ts | 9 ++++++++- test/event-emitter.test.ts | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/source/event-emitter.ts b/source/event-emitter.ts index 3ed7a75..73bf2b7 100644 --- a/source/event-emitter.ts +++ b/source/event-emitter.ts @@ -181,7 +181,12 @@ export class EventEmitter { // Create a listener function. const listener = (payload: Readonly): void => { - if (predicate(payload)) { + try { + // If the event payload does not match the predicate condition, return. + if (!predicate(payload)) { + return; + } + // Clean up this.off(type, listener); if (timeoutId !== undefined) { @@ -189,6 +194,8 @@ export class EventEmitter { } resolve(payload); + } catch (error) { + reject(error); } }; diff --git a/test/event-emitter.test.ts b/test/event-emitter.test.ts index 11d6a3e..dbbd461 100644 --- a/test/event-emitter.test.ts +++ b/test/event-emitter.test.ts @@ -491,6 +491,23 @@ const testEventEmitterDebouncedOnceListener = async (): Promise => { } }; +/** + * Tests that the `waitFor` method rejects if the predicate function throws + */ +const testEventEmitterWaitForRejectsOnPredicateError = async (): Promise => { + const emitter = new EventEmitter(); + const listener = vi.fn(); + + const waitPromise = emitter.waitFor('message', () => { + throw new Error('predicate error'); + }); + + emitter.emit('message', 'hello'); + + await expect(waitPromise).rejects.toThrow('predicate error'); + expect(listener).not.toHaveBeenCalled(); +}; + const runTests = async (): Promise => { test('EventEmitter: calls listeners when an event is emitted', testEventEmitterCallsListeners); test('EventEmitter: calls multiple listeners for the same event', testEventEmitterCallsMultipleListeners); @@ -516,6 +533,7 @@ const runTests = async (): Promise => { test('EventEmitter: resets the debounce timer on repeated emits', testEventEmitterDebouncedTimerResetsOnRepeatedEmits); test('EventEmitter: does not debounce when debounceMilliseconds is zero', testEventEmitterZeroDebounceDoesNotDebounce); test('EventEmitter: debounces once listeners and invokes them only once', testEventEmitterDebouncedOnceListener); + test('EventEmitter: rejects waitFor when the predicate function throws', testEventEmitterWaitForRejectsOnPredicateError); }; await runTests();