Files
Netcatty/infrastructure/ai/errorClassifier.test.ts
T
陈大猫andClaude Opus 4.7 30f5346035 Classify AI proxy / size-limit errors instead of showing raw Zod output (#765) (#768)
Symptom: when an AI request is proxied through nginx (or any gateway)
and the request body exceeds client_max_body_size, the proxy returns a
413 HTML error page. The Vercel AI SDK then fails to parse the HTML
as a chat completion and surfaces a cryptic Zod validation error like
"Expected 'id' to be a string." through the UI — users have no idea
what's wrong.

Root cause: classifyError only did light sanitization and returned the
raw SDK message. It also string-coerced the error before inspection, so
the structured statusCode / responseBody fields that APICallError
attaches were thrown away.

Fix: classifyError now accepts `unknown` and inspects the full error
shape. Adds explicit branches for:

- HTTP 413 (from statusCode, cause.statusCode, or message text) →
  "Request too large — exceeded proxy size limit. Try shorter
  message, fewer attachments, or raise client_max_body_size."
- HTTP 502/503/504 → retryable upstream-gateway message
- HTML response body (starts with <!DOCTYPE/<html> or contains such
  tags anywhere) → "Server returned HTML error page, likely a proxy
  intercept."
- Zod/schema parse shapes ("Expected 'X' to be …", "Invalid JSON
  response", "Type validation failed") → "Response could not be
  parsed; proxy may have replaced/truncated the body."

In every classified case the raw SDK text is still appended ("Raw: …")
so users can report the underlying error verbatim.

useAIChatStreaming.ts callers now pass the raw error to classifyError
instead of `.message`, so the new structured branches actually fire.
Also wired infrastructure/ai/*.test.ts into the npm test glob.

Closes #765

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 22:50:25 +08:00

132 lines
5.4 KiB
TypeScript

import assert from "node:assert/strict";
import test from "node:test";
import { classifyError, sanitizeErrorMessage } from "./errorClassifier.ts";
// -------------------------------------------------------------------
// sanitizeErrorMessage — regression guard for pre-existing behavior
// -------------------------------------------------------------------
test("sanitizeErrorMessage strips absolute user paths", () => {
const result = sanitizeErrorMessage("ENOENT at /Users/alice/project/file.ts");
assert.match(result, /<path>/);
assert.doesNotMatch(result, /alice/);
});
test("sanitizeErrorMessage redacts URL credentials", () => {
const result = sanitizeErrorMessage("Failed https://api.example.com/v1?api_key=SECRET123");
assert.match(result, /<url-redacted>/);
assert.doesNotMatch(result, /SECRET123/);
});
test("sanitizeErrorMessage truncates very long messages", () => {
const long = "a".repeat(1000);
const result = sanitizeErrorMessage(long);
assert.ok(result.length < 600, `expected truncation, got ${result.length} chars`);
assert.match(result, /\.\.\.$/);
});
// -------------------------------------------------------------------
// classifyError — 413 detection
// -------------------------------------------------------------------
test("classifyError surfaces a friendly 413 message when statusCode is 413", () => {
const err = Object.assign(new Error("Request failed with status 413"), {
statusCode: 413,
responseBody: "<html>nginx 413</html>",
});
const info = classifyError(err);
assert.equal(info.type, "network");
assert.match(info.message, /Request too large/i);
assert.match(info.message, /client_max_body_size/i);
assert.match(info.message, /Raw:/);
});
test("classifyError detects 'Request Entity Too Large' in a string error", () => {
const info = classifyError("413 Request Entity Too Large");
assert.equal(info.type, "network");
assert.match(info.message, /Request too large/i);
});
test("classifyError handles 413 via the message when no statusCode field is set", () => {
const info = classifyError(new Error("AI_APICallError: 413 payload rejected"));
assert.equal(info.type, "network");
assert.match(info.message, /Request too large/i);
});
// -------------------------------------------------------------------
// classifyError — 502 / 503 / 504 upstream gateway
// -------------------------------------------------------------------
test("classifyError marks 502/503/504 as network+retryable", () => {
for (const code of [502, 503, 504]) {
const info = classifyError(Object.assign(new Error(`status ${code}`), { statusCode: code }));
assert.equal(info.type, "network");
assert.equal(info.retryable, true, `code ${code} should be retryable`);
assert.match(info.message, new RegExp(String(code)));
}
});
// -------------------------------------------------------------------
// classifyError — HTML response body
// -------------------------------------------------------------------
test("classifyError detects HTML in responseBody even when status is unknown", () => {
const err = Object.assign(new Error("Invalid JSON"), {
responseBody: "<!DOCTYPE html>\n<html><body>nginx error</body></html>",
});
const info = classifyError(err);
assert.equal(info.type, "provider");
assert.match(info.message, /HTML error page/i);
assert.match(info.message, /proxy/i);
});
test("classifyError detects HTML directly embedded in the error message", () => {
const info = classifyError("Parse failed: <html><body>...</body></html>");
assert.equal(info.type, "provider");
assert.match(info.message, /HTML error page/i);
});
// -------------------------------------------------------------------
// classifyError — Zod / schema parse failures
// -------------------------------------------------------------------
test("classifyError surfaces a friendlier message for 'Expected \\'id\\' to be a string.'", () => {
// This is the exact error pattern reported in #765.
const info = classifyError("Expected 'id' to be a string.");
assert.equal(info.type, "provider");
assert.match(info.message, /could not be parsed/i);
assert.match(info.message, /request-size limit/i);
// Raw error must still be visible for debugging / user reports.
assert.match(info.message, /Expected 'id' to be a string/);
});
test("classifyError handles a variety of schema validation wordings", () => {
for (const raw of [
"Invalid JSON response: missing field",
"Type validation failed: expected number",
"Expected 'choices' to be an array.",
]) {
const info = classifyError(raw);
assert.equal(info.type, "provider", `wording: ${raw}`);
assert.match(info.message, /could not be parsed|HTML error page/i);
}
});
// -------------------------------------------------------------------
// classifyError — fallthrough
// -------------------------------------------------------------------
test("classifyError falls through to 'unknown' for unclassified errors", () => {
const info = classifyError(new Error("Some other provider failure"));
assert.equal(info.type, "unknown");
assert.match(info.message, /Some other provider failure/);
});
test("classifyError handles null, undefined, and non-Error shapes without throwing", () => {
assert.doesNotThrow(() => classifyError(null));
assert.doesNotThrow(() => classifyError(undefined));
assert.doesNotThrow(() => classifyError({ foo: "bar" }));
assert.doesNotThrow(() => classifyError(42));
});