Skip to content

Commit

Permalink
Support Error.cause in logging (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiltd authored Oct 17, 2024
1 parent 150501f commit 72ee41c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
27 changes: 27 additions & 0 deletions runtime/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ using api::Engine;
using api::EngineState;
using api::EngineConfig;

void dump_error(JSContext *cx, HandleValue error, bool *has_stack, FILE *fp);

__attribute__((weak))
bool debug_logging_enabled() { return DEBUG_LOGGING; }
#define LOG(...) \
Expand Down Expand Up @@ -116,6 +118,29 @@ bool print_stack(JSContext *cx, FILE *fp) {
return print_stack(cx, stackp, fp);
}

void print_cause(JSContext *cx, HandleValue error, FILE *fp) {
bool has_cause = false;

if (error.isObject()) {
RootedObject err(cx, &error.toObject());
if (!JS_HasProperty(cx, err, "cause", &has_cause)) {
return;
}

if (has_cause) {
JS::RootedValue cause_val(cx);
if (!JS_GetProperty(cx, err, "cause", &cause_val)) {
return;
}

fprintf(stderr, "Caused by: ");

bool has_stack;
dump_error(cx, cause_val, &has_stack, fp);
}
}
}

void dump_error(JSContext *cx, HandleValue error, bool *has_stack, FILE *fp) {
bool reported = false;
RootedObject stack(cx);
Expand Down Expand Up @@ -144,6 +169,8 @@ void dump_error(JSContext *cx, HandleValue error, bool *has_stack, FILE *fp) {
} else {
*has_stack = false;
}

print_cause(cx, error, fp);
}

void dump_promise_rejection(JSContext *cx, HandleValue reason, HandleObject promise, FILE *fp) {
Expand Down
5 changes: 5 additions & 0 deletions tests/e2e/runtime-err/expect_serve_stderr.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,8 @@ stderr [0] :: runtime error
stderr [0] :: Stack:
stderr [0] :: @runtime-err.js:6:13
stderr [0] :: @runtime-err.js:7:7
stderr [0] :: Caused by:
stderr [0] :: error cause
stderr [0] :: Stack:
stderr [0] :: @runtime-err.js:6:49
stderr [0] :: @runtime-err.js:7:7
2 changes: 1 addition & 1 deletion tests/e2e/runtime-err/runtime-err.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { strictEqual, deepStrictEqual, throws } from "../../assert.js";
addEventListener("fetch", (evt) =>
evt.respondWith(
(async () => {
throw new Error('runtime error');
throw new Error('runtime error', { cause: new Error('error cause') });
})()
)
);

0 comments on commit 72ee41c

Please sign in to comment.