Skip to content

Commit

Permalink
Shell: improve handling of unhandled promise rejection
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
2 people authored and gbrail committed Dec 17, 2024
1 parent ba55268 commit 63b6206
Showing 1 changed file with 14 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -643,21 +643,22 @@ private static Script loadCompiledScript(
}
}

private static void printPromiseWarnings(Context cx) {
private static void printPromiseWarnings(Context cx, boolean exitOnRejections) {
List<Object> 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;
}
}
}
Expand Down

0 comments on commit 63b6206

Please sign in to comment.