From 4dbce46ed13578b2dcbf82f8031747ac7c44e650 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sa=C3=BAl=20Ibarra=20Corretg=C3=A9?= <s@saghul.net>
Date: Mon, 6 Jan 2025 11:34:37 +0100
Subject: [PATCH] Exit qjs on unhandled promise rejections

Fixes: https://github.com/quickjs-ng/quickjs/issues/790
---
 qjs.c          | 12 ++----------
 quickjs-libc.c |  2 ++
 2 files changed, 4 insertions(+), 10 deletions(-)

diff --git a/qjs.c b/qjs.c
index a4851bd3c..095bcfdcd 100644
--- a/qjs.c
+++ b/qjs.c
@@ -389,7 +389,6 @@ void help(void)
            "    --exe          select the executable to use as the base, defaults to the current one\n"
            "    --memory-limit n       limit the memory usage to 'n' Kbytes\n"
            "    --stack-size n         limit the stack size to 'n' Kbytes\n"
-           "    --unhandled-rejection  dump unhandled promise rejections\n"
            "-q  --quit         just instantiate the interpreter and quit\n", JS_GetVersion());
     exit(1);
 }
@@ -414,7 +413,6 @@ int main(int argc, char **argv)
     int empty_run = 0;
     int module = -1;
     int load_std = 0;
-    int dump_unhandled_promise_rejection = 0;
     char *include_list[32];
     int i, include_count = 0;
     int64_t memory_limit = -1;
@@ -514,10 +512,6 @@ int main(int argc, char **argv)
                 load_std = 1;
                 continue;
             }
-            if (!strcmp(longopt, "unhandled-rejection")) {
-                dump_unhandled_promise_rejection = 1;
-                continue;
-            }
             if (opt == 'q' || !strcmp(longopt, "quit")) {
                 empty_run++;
                 continue;
@@ -622,10 +616,8 @@ int main(int argc, char **argv)
     /* loader for ES6 modules */
     JS_SetModuleLoaderFunc(rt, NULL, js_module_loader, NULL);
 
-    if (dump_unhandled_promise_rejection) {
-        JS_SetHostPromiseRejectionTracker(rt, js_std_promise_rejection_tracker,
-                                          NULL);
-    }
+    /* exit on unhandled promise rejections */
+    JS_SetHostPromiseRejectionTracker(rt, js_std_promise_rejection_tracker, NULL);
 
     if (!empty_run) {
         js_std_add_helpers(ctx, argc - optind, argv + optind);
diff --git a/quickjs-libc.c b/quickjs-libc.c
index a7b334fbb..620e15ef8 100644
--- a/quickjs-libc.c
+++ b/quickjs-libc.c
@@ -4172,6 +4172,8 @@ void js_std_promise_rejection_tracker(JSContext *ctx, JSValue promise,
     if (!is_handled) {
         fprintf(stderr, "Possibly unhandled promise rejection: ");
         js_std_dump_error1(ctx, reason);
+        fflush(stderr);
+        exit(1);
     }
 }