(err: unknown)
| 3 | import { detectOutputFormat } from "../output/formatter"; |
| 4 | |
| 5 | export function handleError(err: unknown): never { |
| 6 | if (err instanceof CLIError) { |
| 7 | const format = detectOutputFormat(process.env.MINIMAX_OUTPUT); |
| 8 | |
| 9 | if (format === "json") { |
| 10 | process.stderr.write(JSON.stringify(err.toJSON(), null, 2) + "\n"); |
| 11 | } else { |
| 12 | process.stderr.write(`\nError: ${err.message}\n`); |
| 13 | if (err.hint) { |
| 14 | process.stderr.write(`\n ${err.hint.split("\n").join("\n ")}\n`); |
| 15 | } |
| 16 | process.stderr.write(` (exit code ${err.exitCode})\n`); |
| 17 | } |
| 18 | process.exit(err.exitCode); |
| 19 | } |
| 20 | |
| 21 | if (err instanceof Error) { |
| 22 | if ( |
| 23 | err.name === "AbortError" || |
| 24 | err.name === "TimeoutError" || |
| 25 | err.message.includes("timed out") |
| 26 | ) { |
| 27 | const timeout = new CLIError( |
| 28 | "Request timed out.", |
| 29 | ExitCode.TIMEOUT, |
| 30 | "Try increasing --timeout (e.g. --timeout 60).\n" + |
| 31 | "If this happens on every request with a valid API key, you may be hitting the wrong region.\n" + |
| 32 | "Run: mmx auth status — to check your credentials and region.\n" + |
| 33 | "Run: mmx config set region global (or cn) — to override the region.", |
| 34 | ); |
| 35 | return handleError(timeout); |
| 36 | } |
| 37 | |
| 38 | // Detect TypeError from fetch with invalid URL (e.g., malformed MINIMAX_BASE_URL) |
| 39 | if (err instanceof TypeError && err.message === "fetch failed") { |
| 40 | const networkErr = new CLIError( |
| 41 | "Network request failed.", |
| 42 | ExitCode.NETWORK, |
| 43 | "Check your network connection.\n" + |
| 44 | "To use a proxy: set HTTPS_PROXY env var, or run: mmx config set --key proxy --value http://HOST:PORT", |
| 45 | ); |
| 46 | return handleError(networkErr); |
| 47 | } |
| 48 | |
| 49 | // Detect network-level errors (proxy, connection refused, DNS, etc.) |
| 50 | const msg = err.message.toLowerCase(); |
| 51 | const isNetworkError = |
| 52 | msg.includes("failed to fetch") || |
| 53 | msg.includes("connection refused") || |
| 54 | msg.includes("econnrefused") || |
| 55 | msg.includes("connection reset") || |
| 56 | msg.includes("econnreset") || |
| 57 | msg.includes("network error") || |
| 58 | msg.includes("enotfound") || |
| 59 | msg.includes("getaddrinfo") || |
| 60 | msg.includes("proxy") || |
| 61 | msg.includes("socket") || |
| 62 | msg.includes("etimedout") || |
no test coverage detected