Browse Source

feat: catch siteevent and interface event errors

Sv443 9 months ago
parent
commit
dcba600184
2 changed files with 23 additions and 13 deletions
  1. 9 4
      src/interface.ts
  2. 14 9
      src/siteEvents.ts

+ 9 - 4
src/interface.ts

@@ -209,10 +209,15 @@ export function emitInterface<
   type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
   ...detail: (TDetail extends undefined ? [undefined?] : [TDetail])
 ) {
-  getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: detail?.[0] ?? undefined }));
-  //@ts-ignore
-  emitOnPlugins(type, undefined, ...detail);
-  log(`Emitted interface event '${type}'${detail.length > 0 && detail?.[0] ? " with data:" : ""}`, ...detail);
+  try {
+    getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: detail?.[0] ?? undefined }));
+    //@ts-ignore
+    emitOnPlugins(type, undefined, ...detail);
+    log(`Emitted interface event '${type}'${detail.length > 0 && detail?.[0] ? " with data:" : ""}`, ...detail);
+  }
+  catch(err) {
+    error(`Couldn't emit interface event '${type}' due to an error:\n`, err);
+  }
 }
 
 //#region register plugins

+ 14 - 9
src/siteEvents.ts

@@ -201,7 +201,7 @@ export async function initSiteEvents() {
     });
   }
   catch(err) {
-    error("Couldn't initialize SiteEvents observers due to an error:\n", err);
+    error("Couldn't initialize site event observers due to an error:\n", err);
   }
 }
 
@@ -210,15 +210,20 @@ window.addEventListener("bytm:ready", () => bytmReady = true, { once: true });
 
 /** Emits a site event with the given key and arguments - if `bytm:ready` has not been emitted yet, all events will be queued until it is */
 export function emitSiteEvent<TKey extends keyof SiteEventsMap>(key: TKey, ...args: Parameters<SiteEventsMap[TKey]>) {
-  if(!bytmReady) {
-    window.addEventListener("bytm:ready", () => {
-      bytmReady = true;
-      emitSiteEvent(key, ...args);
-    }, { once: true });
-    return;
+  try {
+    if(!bytmReady) {
+      window.addEventListener("bytm:ready", () => {
+        bytmReady = true;
+        emitSiteEvent(key, ...args);
+      }, { once: true });
+      return;
+    }
+    siteEvents.emit(key, ...args);
+    emitInterface(`bytm:siteEvent:${key}`, args as unknown as undefined);
+  }
+  catch(err) {
+    error(`Couldn't emit site event "${key}" due to an error:\n`, err);
   }
-  siteEvents.emit(key, ...args);
-  emitInterface(`bytm:siteEvent:${key}`, args as unknown as undefined);
 }
 
 //#region other