From 4b4d82f33f2fb24ad40106c7ed4cf0f472b96e6f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jo=C3=A3o=20Magalh=C3=A3es?= <joamag@gmail.com>
Date: Fri, 19 May 2023 00:04:39 +0100
Subject: [PATCH] fix: safer re-setting of the pacic hook In some versions of
 WASM-bindgen the re-setting of the hook from the current panicking thread
 would fail.

---
 frontends/web/ts/gb.ts | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/frontends/web/ts/gb.ts b/frontends/web/ts/gb.ts
index 20a58b9a..5dec68fd 100644
--- a/frontends/web/ts/gb.ts
+++ b/frontends/web/ts/gb.ts
@@ -237,11 +237,10 @@ export class GameboyEmulator extends EmulatorBase implements Emulator {
                 this.pause();
 
                 // if we're talking about a panic, proper action must be taken
-                // which in this case it means restarting both the WASM sub
+                // which in this case means restarting both the WASM sub
                 // system and the machine state (to be able to recover)
-                // also sets the default color on screen to indicate the issue
                 if (isPanic) {
-                    await wasm();
+                    await wasm(true);
                     await this.boot({ restore: false });
 
                     this.trigger("error");
@@ -957,7 +956,19 @@ console.image = (url: string, size = 80) => {
     console.log("%c     ", style);
 };
 
-const wasm = async () => {
+const wasm = async (setHook = true) => {
     await _wasm();
-    GameBoy.set_panic_hook_ws();
+
+    // in case the set hook flag is set, then tries to
+    // set the panic hook for the WASM module, this call
+    // may fail in some versions of wasm-bindgen as the
+    // thread is still marked as "panicking", so we need to
+    // wrap the call around try/catch
+    if (setHook) {
+        try {
+            GameBoy.set_panic_hook_ws();
+        } catch (err) {
+            console.error(err);
+        }
+    }
 };
-- 
GitLab