fix(#965): emit structured json error for unexpected handler throws under --json-errors (#987)

* fix(#965): emit structured json error for unexpected handler throws under --json-errors

When GSD_JSON_ERRORS=1 / --json-errors is active, an unexpected (non-ExitError) throw
in a handler now emits { ok: false, reason: "sdk_fail_fast", message } to stderr instead
of a raw stack trace. The plain-text behaviour (no json-error mode) is unchanged.

Closes #965

* chore(#965): backfill changeset pr number (987)

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Tom Boucher
2026-06-10 10:40:12 -04:00
committed by GitHub
parent 626575cbc5
commit 22bb82e205
3 changed files with 112 additions and 3 deletions

View File

@@ -1,3 +1,8 @@
import fs from 'node:fs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import ioModule = require('./io.cjs');
const { getJsonErrorMode, ERROR_REASON } = ioModule;
/**
* Error carrying a process exit code. CLI logic throws this instead of calling
* process.exit() (banned by n/no-process-exit); runMain() translates it into
@@ -20,7 +25,8 @@ class ExitError extends Error {
* process.on('exit') cleanup still fires). main may be sync or async:
* number return -> process.exitCode = it
* thrown ExitError -> process.exitCode = err.code (+ stderr err.message if hasUserMessage && code!=0)
* other throw -> stderr stack + process.exitCode = 1
* other throw -> when json-error mode is active, emits structured { ok:false, reason, message }
* to stderr; otherwise writes raw stack trace. exit code = 1 in either case.
*/
function runMain(main: () => number | void | Promise<number | void>): void {
Promise.resolve()
@@ -32,8 +38,18 @@ function runMain(main: () => number | void | Promise<number | void>): void {
process.exitCode = err.code;
return;
}
const e = err as Error;
process.stderr.write(`${e && e.stack ? e.stack : String(err)}\n`);
if (getJsonErrorMode()) {
const e = err as Error;
const payload = JSON.stringify({
ok: false,
reason: ERROR_REASON.SDK_FAIL_FAST,
message: (e && e.message) ? e.message : String(err),
}) + '\n';
fs.writeSync(2, payload);
} else {
const e = err as Error;
process.stderr.write(`${e && e.stack ? e.stack : String(err)}\n`);
}
process.exitCode = 1;
});
}