xonecas.io
64875
Mc

mini-coder / commit db7029e

feat: better error logging and parsing

Implement structured error logging to file and friendly error parsing for display as planned in better-errors.md.

Sean2026-03-01 db7029ec0f4331c96e4f7b3a8b3f0841c8124d85 parent ec0abd1

5 files changed

src/cli/error-log.ts+55−0
@@ -0,0 +1,55 @@
1+import { mkdirSync } from "node:fs";
2+import { homedir } from "node:os";
3+import { join } from "node:path";
4+
5+let writer: ReturnType<ReturnType<typeof Bun.file>["writer"]> | null = null;
6+
7+export function initErrorLog(): void {
8+ if (writer) return;
9+
10+ const dirPath = join(homedir(), ".config", "mini-coder");
11+ const logPath = join(dirPath, "errors.log");
12+
13+ mkdirSync(dirPath, { recursive: true });
14+
15+ // Truncate on open
16+ writer = Bun.file(logPath).writer();
17+
18+ process.on("uncaughtException", (err) => {
19+ logError(err, "uncaught");
20+ process.exit(1);
21+ });
22+}
23+
24+function isObject(v: unknown): v is Record<string, unknown> {
25+ return typeof v === "object" && v !== null;
26+}
27+
28+export function logError(err: unknown, context?: string): void {
29+ if (!writer) return;
30+
31+ let entry = `[${new Date().toISOString()}]`;
32+ if (context) entry += ` context=${context}`;
33+ entry += "\n";
34+
35+ if (isObject(err)) {
36+ if (typeof err.name === "string") entry += ` name: ${err.name}\n`;
37+ if (typeof err.message === "string") entry += ` message: ${err.message}\n`;
38+ if ("statusCode" in err) entry += ` statusCode: ${err.statusCode}\n`;
39+ if ("url" in err) entry += ` url: ${err.url}\n`;
40+ if ("isRetryable" in err) entry += ` isRetryable: ${err.isRetryable}\n`;
41+ if (typeof err.stack === "string") {
42+ const indentedStack = err.stack
43+ .split("\n")
44+ .map((line, i) => (i === 0 ? line : ` ${line}`))
45+ .join("\n");
46+ entry += ` stack: ${indentedStack}\n`;
47+ }
48+ } else {
49+ entry += ` value: ${String(err)}\n`;
50+ }
51+
52+ entry += "---\n";
53+ writer.write(entry);
54+ writer.flush();
55+}
src/cli/error-parse.test.ts+120−0
@@ -0,0 +1,120 @@
1+import { expect, test } from "bun:test";
2+import {
3+ APICallError,
4+ LoadAPIKeyError,
5+ NoContentGeneratedError,
6+ NoSuchModelError,
7+ RetryError,
8+} from "ai";
9+import { parseAppError } from "./error-parse.ts";
10+
11+test("parseAppError - string", () => {
12+ expect(parseAppError("hello world")).toEqual({ headline: "hello world" });
13+});
14+
15+test("parseAppError - APICallError 429", () => {
16+ const err = new APICallError({
17+ message: "Too many",
18+ statusCode: 429,
19+ url: "https://api.example.com",
20+ requestBodyValues: {},
21+ });
22+ expect(parseAppError(err)).toEqual({
23+ headline: "Rate limit hit",
24+ hint: "Wait a moment and retry, or switch model with /model",
25+ });
26+});
27+
28+test("parseAppError - APICallError 401", () => {
29+ const err = new APICallError({
30+ message: "Unauthorized",
31+ statusCode: 401,
32+ url: "https://api.example.com",
33+ requestBodyValues: {},
34+ });
35+ expect(parseAppError(err)).toEqual({
36+ headline: "Auth failed",
37+ hint: "Check the relevant provider API key env var",
38+ });
39+});
40+
41+test("parseAppError - APICallError generic", () => {
42+ const err = new APICallError({
43+ message: "Bad Gateway",
44+ statusCode: 502,
45+ url: "https://api.example.com",
46+ requestBodyValues: {},
47+ });
48+ expect(parseAppError(err)).toEqual({
49+ headline: "API error 502",
50+ hint: "https://api.example.com",
51+ });
52+});
53+
54+test("parseAppError - RetryError", () => {
55+ const inner = new APICallError({
56+ message: "Rate limit",
57+ statusCode: 429,
58+ url: "https://api.example.com",
59+ requestBodyValues: {},
60+ });
61+ const err = new RetryError({
62+ message: "Retries failed",
63+ reason: "maxRetriesExceeded",
64+ errors: [inner],
65+ });
66+ expect(parseAppError(err)).toEqual({
67+ headline: "Retries exhausted: Rate limit hit",
68+ hint: "Wait a moment and retry, or switch model with /model",
69+ });
70+});
71+
72+test("parseAppError - NoContentGeneratedError", () => {
73+ const err = new NoContentGeneratedError({ message: "Empty" });
74+ expect(parseAppError(err)).toEqual({
75+ headline: "Model returned empty response",
76+ hint: "Try rephrasing or switching model with /model",
77+ });
78+});
79+
80+test("parseAppError - LoadAPIKeyError", () => {
81+ const err = new LoadAPIKeyError({ message: "Missing key" });
82+ expect(parseAppError(err)).toEqual({
83+ headline: "API key not found",
84+ hint: "Set the relevant provider env var",
85+ });
86+});
87+
88+test("parseAppError - NoSuchModelError", () => {
89+ const err = new NoSuchModelError({
90+ modelId: "gpt-4",
91+ modelType: "languageModel",
92+ });
93+ expect(parseAppError(err)).toEqual({
94+ headline: "Model not found",
95+ hint: "Use /model to pick a valid model",
96+ });
97+});
98+
99+test("parseAppError - ECONNREFUSED code", () => {
100+ const err = Object.assign(new Error("Boom"), { code: "ECONNREFUSED" });
101+ expect(parseAppError(err)).toEqual({
102+ headline: "Connection failed",
103+ hint: "Check network or local server",
104+ });
105+});
106+
107+test("parseAppError - ECONNREFUSED message", () => {
108+ const err = new Error("fetch failed: ECONNREFUSED 127.0.0.1:11434");
109+ expect(parseAppError(err)).toEqual({
110+ headline: "Connection failed",
111+ hint: "Check network or local server",
112+ });
113+});
114+
115+test("parseAppError - fallback", () => {
116+ const err = new Error("Something went wrong\nSome more details");
117+ expect(parseAppError(err)).toEqual({
118+ headline: "Something went wrong",
119+ });
120+});
src/cli/error-parse.ts+78−0
@@ -0,0 +1,78 @@
1+import {
2+ APICallError,
3+ LoadAPIKeyError,
4+ NoContentGeneratedError,
5+ NoSuchModelError,
6+ RetryError,
7+} from "ai";
8+
9+export function parseAppError(err: unknown): {
10+ headline: string;
11+ hint?: string;
12+} {
13+ if (typeof err === "string") {
14+ return { headline: err };
15+ }
16+
17+ if (err instanceof RetryError) {
18+ const inner = parseAppError(err.lastError);
19+ return {
20+ headline: `Retries exhausted: ${inner.headline}`,
21+ ...(inner.hint ? { hint: inner.hint } : {}),
22+ };
23+ }
24+
25+ if (err instanceof APICallError) {
26+ if (err.statusCode === 429) {
27+ return {
28+ headline: "Rate limit hit",
29+ hint: "Wait a moment and retry, or switch model with /model",
30+ };
31+ }
32+ if (err.statusCode === 401 || err.statusCode === 403) {
33+ return {
34+ headline: "Auth failed",
35+ hint: "Check the relevant provider API key env var",
36+ };
37+ }
38+ return {
39+ headline: `API error ${err.statusCode ?? "unknown"}`,
40+ ...(err.url ? { hint: err.url } : {}),
41+ };
42+ }
43+
44+ if (err instanceof NoContentGeneratedError) {
45+ return {
46+ headline: "Model returned empty response",
47+ hint: "Try rephrasing or switching model with /model",
48+ };
49+ }
50+
51+ if (err instanceof LoadAPIKeyError) {
52+ return {
53+ headline: "API key not found",
54+ hint: "Set the relevant provider env var",
55+ };
56+ }
57+
58+ if (err instanceof NoSuchModelError) {
59+ return {
60+ headline: "Model not found",
61+ hint: "Use /model to pick a valid model",
62+ };
63+ }
64+
65+ const isObj = typeof err === "object" && err !== null;
66+ const code = isObj && "code" in err ? String(err.code) : undefined;
67+ const message = isObj && "message" in err ? String(err.message) : String(err);
68+
69+ if (code === "ECONNREFUSED" || message.includes("ECONNREFUSED")) {
70+ return {
71+ headline: "Connection failed",
72+ hint: "Check network or local server",
73+ };
74+ }
75+
76+ const firstLine = message.split("\n")[0]?.trim() || "Unknown error";
77+ return { headline: firstLine };
78+}
src/cli/output.ts+21−7
@@ -4,6 +4,8 @@ import * as c from "yoctocolors";
44 import type { CoreMessage } from "../llm-api/turn.ts";
55 import type { TurnEvent } from "../llm-api/types.ts";
66 import type { SubagentOutput } from "../tools/subagent.ts";
7+import { logError } from "./error-log.ts";
8+import { parseAppError } from "./error-parse.ts";
79 import { renderChunk } from "./markdown.ts";
810
911 const HOME = homedir();
@@ -386,8 +388,12 @@ export function renderSubagentEvent(
386388 }
387389 } else if (event.type === "turn-error") {
388390 laneBuffers.delete(laneId);
389- const msg = event.error.message.split("\n")[0] ?? event.error.message;
390- writeln(`${prefix}${G.err} ${c.red(msg)}`);
391+ logError(event.error, "turn");
392+ const parsed = parseAppError(event.error);
393+ writeln(`${prefix}${G.err} ${c.red(parsed.headline)}`);
394+ if (parsed.hint) {
395+ writeln(`${prefix} ${c.dim(parsed.hint)}`);
396+ }
391397 }
392398 }
393399
@@ -765,8 +771,12 @@ export async function renderTurn(
765771 if (isAbort) {
766772 writeln(`${G.warn} ${c.dim("interrupted")}`);
767773 } else {
768- const msg = event.error.message.split("\n")[0] ?? event.error.message;
769- writeln(`${G.err} ${c.red(msg)}`);
774+ logError(event.error, "turn");
775+ const parsed = parseAppError(event.error);
776+ writeln(`${G.err} ${c.red(parsed.headline)}`);
777+ if (parsed.hint) {
778+ writeln(` ${c.dim(parsed.hint)}`);
779+ }
770780 }
771781 break;
772782 }
@@ -852,9 +862,13 @@ export function renderBanner(model: string, cwd: string): void {
852862
853863 // ─── Error / info helpers ─────────────────────────────────────────────────────
854864
855-export function renderError(err: unknown): void {
856- const msg = err instanceof Error ? err.message : String(err);
857- writeln(`${G.err} ${c.red(msg)}`);
865+export function renderError(err: unknown, context = "render"): void {
866+ logError(err, context);
867+ const parsed = parseAppError(err);
868+ writeln(`${G.err} ${c.red(parsed.headline)}`);
869+ if (parsed.hint) {
870+ writeln(` ${c.dim(parsed.hint)}`);
871+ }
858872 }
859873
860874 export function renderInfo(msg: string): void {
src/index.ts+4−2
@@ -1,6 +1,7 @@
11 #!/usr/bin/env bun
22 import * as c from "yoctocolors";
33 import { runAgent } from "./agent/agent.ts";
4+import { initErrorLog } from "./cli/error-log.ts";
45 import {
56 registerTerminalCleanup,
67 renderBanner,
@@ -14,6 +15,7 @@ import { getMostRecentSession, printSessionList } from "./session/manager.ts";
1415 // Register terminal cleanup handlers as early as possible so the cursor is
1516 // always restored even if the process crashes or is killed.
1617 registerTerminalCleanup();
18+initErrorLog();
1719
1820 // ─── CLI argument parsing ─────────────────────────────────────────────────────
1921
@@ -159,12 +161,12 @@ async function main(): Promise<void> {
159161 if (args.prompt) agentOpts.initialPrompt = args.prompt;
160162 await runAgent(agentOpts);
161163 } catch (err) {
162- renderError(err);
164+ renderError(err, "agent");
163165 process.exit(1);
164166 }
165167 }
166168
167169 main().catch((err) => {
168- console.error(err);
170+ renderError(err, "main");
169171 process.exit(1);
170172 });