refactor(errors): extract top-level error handling into shared utility

This commit is contained in:
mitchell 2026-06-17 00:48:15 -04:00
parent 56352d87ec
commit f8e0f9a368
3 changed files with 26 additions and 16 deletions

View file

@ -2,11 +2,10 @@
import util from "node:util"; import util from "node:util";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { streamText } from "ai"; import { streamText } from "ai";
import chalk from "chalk";
import wrapAnsi from "wrap-ansi";
import { initConfig, loadConfig } from "./src/config"; import { initConfig, loadConfig } from "./src/config";
import { Conversation } from "./src/conversation"; import { Conversation } from "./src/conversation";
import { handleTopLevel } from "./src/errors";
import Renderer from "./src/render"; import Renderer from "./src/render";
async function main() { async function main() {
@ -104,10 +103,4 @@ Review the above diff for any potential bugs, best practices, performance issues
await renderer.renderStats(totalUsage); await renderer.renderStats(totalUsage);
} }
main().catch((err) => { main().catch(handleTopLevel);
if ("message" in err) {
const [columns] = process.stderr.getWindowSize();
console.error(wrapAnsi(chalk.red(err.message), columns));
} else console.log(err);
process.exit(1);
});

22
src/errors.ts Normal file
View file

@ -0,0 +1,22 @@
import { chalkStderr } from "chalk";
import wrapAnsi from "wrap-ansi";
export function handleTopLevel(err: unknown) {
if (
typeof err === "object" &&
err !== null &&
"message" in err &&
typeof err.message === "string"
) {
if (process.stderr.isTTY) {
const [columns] = process.stderr.getWindowSize();
console.error(wrapAnsi(chalkStderr.red(err.message), columns));
} else {
console.error(err.message);
}
} else {
console.error(String(err));
}
process.exit(1);
}

9
tts.ts
View file

@ -11,6 +11,7 @@ import chalk from "chalk";
import { execa } from "execa"; import { execa } from "execa";
import { Window } from "happy-dom"; import { Window } from "happy-dom";
import wrapAnsi from "wrap-ansi"; import wrapAnsi from "wrap-ansi";
import { handleTopLevel } from "./src/errors";
async function main() { async function main() {
const start = Date.now(); const start = Date.now();
@ -179,10 +180,4 @@ async function main() {
})`mpv --pause output.wav`; })`mpv --pause output.wav`;
} }
main().catch((err) => { main().catch(handleTopLevel);
if ("message" in err) {
const [columns] = process.stderr.getWindowSize();
console.error(wrapAnsi(chalk.red(err.message), columns));
} else console.log(err);
process.exit(1);
});