From 55fb81867be16d9eade44727e34a17c68f7b506b Mon Sep 17 00:00:00 2001
From: dan <dan.abramov@gmail.com>
Date: Thu, 21 Mar 2024 17:01:55 +0000
Subject: [Statsig] Protect against early logEvent call crashing (#3315)

* [Statsig] Check if initialized

* Never interrupt the caller
---
 src/lib/statsig/statsig.tsx | 20 +++++++++++++++-----
 1 file changed, 15 insertions(+), 5 deletions(-)

(limited to 'src/lib/statsig/statsig.tsx')

diff --git a/src/lib/statsig/statsig.tsx b/src/lib/statsig/statsig.tsx
index 9bccedc6e..a9d69fda7 100644
--- a/src/lib/statsig/statsig.tsx
+++ b/src/lib/statsig/statsig.tsx
@@ -46,11 +46,21 @@ export function logEvent<E extends keyof LogEvents>(
   eventName: E & string,
   rawMetadata: LogEvents[E] & FlatJSONRecord,
 ) {
-  const fullMetadata = {
-    ...rawMetadata,
-  } as Record<string, string> // Statsig typings are unnecessarily strict here.
-  fullMetadata.routeName = getCurrentRouteName() ?? '(Uninitialized)'
-  Statsig.logEvent(eventName, null, fullMetadata)
+  try {
+    const fullMetadata = {
+      ...rawMetadata,
+    } as Record<string, string> // Statsig typings are unnecessarily strict here.
+    fullMetadata.routeName = getCurrentRouteName() ?? '(Uninitialized)'
+    if (Statsig.initializeCalled()) {
+      Statsig.logEvent(eventName, null, fullMetadata)
+    }
+  } catch (e) {
+    // A log should never interrupt the calling code, whatever happens.
+    // Rethrow on a clean stack.
+    setTimeout(() => {
+      throw e
+    })
+  }
 }
 
 export function useGate(gateName: string) {
-- 
cgit 1.4.1

