From 693f882f5aecd672db4564c22d6d2409d9346677 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Rapha=C3=ABl=20Bideau?=
 <7304827+rbideau@users.noreply.github.com>
Date: Fri, 14 Jun 2024 13:38:57 +0200
Subject: [PATCH] catch post request variable evaluation errors (#2324)

fix #2005

- display post request variable evaluation errors in a toast, each individual variable error on a new line
- display the response body (was previously replaced by the an error "Error invoking remote method 'send-http-request': ..."
---
 .../bruno-electron/src/ipc/network/index.js   |  4 ++++
 packages/bruno-js/src/runtime/vars-runtime.js | 19 ++++++++++++++++---
 2 files changed, 20 insertions(+), 3 deletions(-)

diff --git a/packages/bruno-electron/src/ipc/network/index.js b/packages/bruno-electron/src/ipc/network/index.js
index 5d2e002308..0a5fee7758 100644
--- a/packages/bruno-electron/src/ipc/network/index.js
+++ b/packages/bruno-electron/src/ipc/network/index.js
@@ -401,6 +401,10 @@ const registerNetworkIpc = (mainWindow) => {
           collectionUid
         });
       }
+
+      if (result?.error) {
+        mainWindow.webContents.send('main:display-error', result.error);
+      }
     }
 
     // run post-response script
diff --git a/packages/bruno-js/src/runtime/vars-runtime.js b/packages/bruno-js/src/runtime/vars-runtime.js
index 0185ebddc7..7708222130 100644
--- a/packages/bruno-js/src/runtime/vars-runtime.js
+++ b/packages/bruno-js/src/runtime/vars-runtime.js
@@ -56,14 +56,27 @@ class VarsRuntime {
       ...bruContext
     };
 
+    const errors = new Map();
     _.each(enabledVars, (v) => {
-      const value = evaluateJsExpression(v.value, context);
-      bru.setVar(v.name, value);
+      try {
+        const value = evaluateJsExpression(v.value, context);
+        bru.setVar(v.name, value);
+      } catch (error) {
+        errors.set(v.name, error);
+      }
     });
 
+    let error = null;
+    if (errors.size > 0) {
+      // Format all errors as a single string to be displayed in a toast
+      const errorMessage = [...errors.entries()].map(([name, err]) => `${name}: ${err.message ?? err}`).join('\n');
+      error = `${errors.size} error${errors.size === 1 ? '' : 's'} in post response variables: \n${errorMessage}`;
+    }
+
     return {
       envVariables,
-      collectionVariables
+      collectionVariables,
+      error
     };
   }
 }