fix: keep the real error when a Bun script throws a cyclic error (#12232)

* fix: keep the real error when a Bun script throws a cyclic error

The Bun wrapper copies a thrown error's own properties into `extra` and
JSON-encodes the result. When one of them is cyclic (AWS SDK v3 errors'
`$response`), the encoding threw and the job error became
"cannot serialize cyclic structures". Fall back to an encoding that
replaces back-references with "[Circular]", keeping the plain encoding
first so non-cyclic errors are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: replace only the unencodable fields of a Bun error's extra

Encode each field of `extra` on its own when the whole error fails, and
replace the ones that throw with "[unserializable]". Simpler than walking
cycles, and drops noise like AWS's `$response` while keeping `Code` and
`$metadata`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-11-05 23:29:19 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent c057f8995d
commit 9cd04d0a88
2 changed files with 25 additions and 3 deletions
+6 -1
View File
@@ -330,7 +330,10 @@ async fn test_bun_job_runtime_error(db: Pool<Postgres>) -> anyhow::Result<()> {
let content = r#"
export function main() {
throw new Error("intentional error");
const e = new Error("intentional error");
e.Code = "X";
e.self = e;
throw e;
}
"#
.to_owned();
@@ -361,6 +364,8 @@ export function main() {
.as_str()
.unwrap()
.contains("intentional error"));
assert_eq!(error["extra"]["Code"], "X");
assert_eq!(error["extra"]["self"], "[unserializable]");
Ok(())
}
+19 -2
View File
@@ -85,6 +85,23 @@ pub const BUN_LOCKB_SPLIT_WINDOWS: &str = "\r\n//bun.lockb\r\n";
pub const EMPTY_FILE: &str = "<empty>";
/// A thrown error's own properties (`extra`) can be cyclic, e.g. AWS SDK v3's `$response`:
/// a plain `JSON.stringify` then throws and the real error is lost. The fallback replaces
/// only the fields that cannot be encoded, so the rest (`Code`, `$metadata`, ...) survive.
const STRINGIFY_ERROR_JS: &str = r#"(() => {
try {
return JSON.stringify(err);
} catch {}
for (const k of Object.keys(err.extra ?? {})) {
try {
JSON.stringify(err.extra[k]);
} catch {
err.extra[k] = '[unserializable]';
}
}
return JSON.stringify(err);
})()"#;
/// Bun args for dedicated worker (without the script path)
pub const BUN_DEDICATED_WORKER_ARGS: &[&str] = &["run", "-i", "--prefer-offline"];
@@ -2870,7 +2887,7 @@ try {{
if (Object.keys(extra).length > 0) {{
err["extra"] = extra;
}}
await fs.writeFile("result.json", JSON.stringify(err));
await fs.writeFile("result.json", {STRINGIFY_ERROR_JS});
process.exit(1);
}}
"#,
@@ -2944,7 +2961,7 @@ try {{
if (Object.keys(extra).length > 0) {{
err["extra"] = extra;
}}
await fs.writeFile("result.json", JSON.stringify(err));
await fs.writeFile("result.json", {STRINGIFY_ERROR_JS});
process.exit(1);
}}
"#,