From 63b620605a00f7653bb6aa1fd6b5057fc0b84021 Mon Sep 17 00:00:00 2001 From: "andrea.bergia" Date: Fri, 13 Dec 2024 12:37:23 +0100 Subject: [PATCH] Shell: improve handling of unhandled promise rejection We have changed the logging to log _all_ the exceptions, rather than just the first one. Also, we quit the process with non-zero status if we are evaluating a file (i.e. not in REPL mode) and there are any unhandled promise rejections. Co-authored-by: Satish Srinivasan --- .../mozilla/javascript/tools/shell/Main.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/rhino-tools/src/main/java/org/mozilla/javascript/tools/shell/Main.java b/rhino-tools/src/main/java/org/mozilla/javascript/tools/shell/Main.java index f67d0d8798..698b5b382f 100644 --- a/rhino-tools/src/main/java/org/mozilla/javascript/tools/shell/Main.java +++ b/rhino-tools/src/main/java/org/mozilla/javascript/tools/shell/Main.java @@ -96,7 +96,7 @@ public Object run(Context cx) { } if (type == PROCESS_FILES) { processFiles(cx, args); - printPromiseWarnings(cx); + printPromiseWarnings(cx, true); } else if (type == EVAL_INLINE_SCRIPT) { evalInlineScript(cx, scriptText); } else { @@ -494,7 +494,7 @@ public static void processSource(Context cx, String filename) throws IOException NativeArray h = global.history; h.put((int) h.getLength(), h, source); } - printPromiseWarnings(cx); + printPromiseWarnings(cx, false); } catch (RhinoException rex) { ToolErrorReporter.reportException(cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; @@ -643,21 +643,22 @@ private static Script loadCompiledScript( } } - private static void printPromiseWarnings(Context cx) { + private static void printPromiseWarnings(Context cx, boolean exitOnRejections) { List unhandled = cx.getUnhandledPromiseTracker().enumerate(); if (!unhandled.isEmpty()) { - Object result = unhandled.get(0); - String msg = "Unhandled rejected promise: " + Context.toString(result); - if (result instanceof Scriptable) { - Object stack = ScriptableObject.getProperty((Scriptable) result, "stack"); - if (stack != null && stack != Scriptable.NOT_FOUND) { - msg += '\n' + Context.toString(stack); + for (Object rejection : unhandled) { + String msg = "Unhandled rejected promise: " + Context.toString(rejection); + if (rejection instanceof Scriptable) { + Object stack = ScriptableObject.getProperty((Scriptable) rejection, "stack"); + if (stack != null && stack != Scriptable.NOT_FOUND) { + msg += '\n' + Context.toString(stack); + } } + System.out.println(msg); } - System.out.println(msg); - if (unhandled.size() > 1) { - System.out.println( - " and " + (unhandled.size() - 1) + " other unhandled rejected promises"); + + if (exitOnRejections) { + exitCode = EXITCODE_RUNTIME_ERROR; } } }