From ea87d133427b9b2d257d8afafffc6bb95cbaa1fa Mon Sep 17 00:00:00 2001 From: deyu <40905802+Xdy1579883916@users.noreply.github.com> Date: Fri, 15 Nov 2024 00:43:40 +0800 Subject: [PATCH] feat(messaging): add breakError to the config (#77) (#81) --- .gitignore | 1 + packages/messaging/src/generic.ts | 4 ++++ packages/messaging/src/types.ts | 7 +++++++ 3 files changed, 12 insertions(+) diff --git a/.gitignore b/.gitignore index 6c27d90..4f98f22 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ tsconfig.vitest-temp.json /.cache .output .wxt +.idea diff --git a/packages/messaging/src/generic.ts b/packages/messaging/src/generic.ts index 842677b..41476fc 100644 --- a/packages/messaging/src/generic.ts +++ b/packages/messaging/src/generic.ts @@ -136,6 +136,10 @@ export function defineGenericMessanging< removeRootListener = config.addRootListener(message => { // Validate the message object if (typeof message.type != 'string' || typeof message.timestamp !== 'number') { + // #77 When the message is invalid, we stop processing the message using return or throw an error (default) + if (config.breakError) { + return; + } const err = Error( `[messaging] Unknown message format, must include the 'type' & 'timestamp' fields, received: ${JSON.stringify( message, diff --git a/packages/messaging/src/types.ts b/packages/messaging/src/types.ts index f340f0b..8ec0ce8 100644 --- a/packages/messaging/src/types.ts +++ b/packages/messaging/src/types.ts @@ -77,6 +77,13 @@ export interface BaseMessagingConfig { * @default console */ logger?: Logger; + + /** + * Whether to break an error when an invalid message is received. + * + * @default undefined + */ + breakError?: boolean; } export interface NamespaceMessagingConfig extends BaseMessagingConfig {