JuliusBrussee/caveman · error · CaveRequestError

cave response was not valid JSON

Error message

cave response was not valid JSON

What it means

Thrown when the Cave server's response body cannot be parsed as JSON by the shared caveFetch helper — either JSON.parse fails on the text body, or response.json() itself rejects. The helper deliberately collapses the missing-decoder case and any parse failure into this single CaveRequestError carrying the HTTP status and path, since a Cave endpoint must always answer with JSON.

Solutions

  1. Log err.status and err.path, then curl the same URL to inspect the raw body being returned
  2. Verify baseURL is the Cave API root, not a proxy, gateway, or marketing domain
  3. Check intermediary infrastructure (nginx, Cloudflare, corporate proxy) for HTML error pages or body rewriting
  4. Retry on transient gateway errors (502/503/504) with exponential backoff

Example fix

// before
const data = await sdk.getStats(); // CaveRequestError: cave response was not valid JSON
// after
try {
  const data = await sdk.getStats();
} catch (err) {
  if (err instanceof CaveRequestError && /not valid JSON/.test(err.message)) {
    console.error(`non-JSON body from ${err.path} (status ${err.status}) — check gateway/proxy`);
  }
  throw err;
}
Defensive patterns

Strategy: try-catch

Validate before calling

// pre-flight: const res = await fetch(baseURL + '/sdk/v1/health'); await res.json(); // throws if non-JSON

Try / catch

try { const r = await sdk.call(); } catch (e) { if (e instanceof CaveRequestError && e.message.includes('not valid JSON')) { log.error(`gateway returned non-JSON for ${e.path} (${e.status})`); return retryWithBackoff(); } throw e; }

Prevention

When it happens

Trigger: Server returns HTML error page (e.g. reverse-proxy 502 page from nginx/Cloudflare), an empty body with 200, a gzip/encoding mismatch, or a truncated response; also text/plain responses from an endpoint behind a misconfigured gateway.

Common situations: baseURL accidentally pointing at a landing page or a proxy instead of the Cave API; load balancer returning HTML 502/504 pages during outages; corporate proxy intercepting requests; server crash mid-response.

Understand the failure class

Background: "Invalid JSON response" and "Failed to parse response" errors: when an API answers 200 but the body isn't the JSON your library expected — this error's family across 28 libraries.

Related errors


AI-assisted analysis of JuliusBrussee/caveman@3ee70a1026 (2026-09-20). Data as JSON: /api/errors/8a0ae92d389da001. Report an issue: GitHub.

Appendix: source

Thrown at packages/sdk/typescript/src/index.ts:2135

    headers: { ...headers(cave, workflow ?? cave.options.defaultWorkflow ?? "unlabeled-workflow", undefined, undefined, trace), ...extraHeaders }
  };
  if (body !== undefined) init.body = JSON.stringify(body);
  const response = await caveFetch(cave, `${cave.options.baseURL}${path}`, init);
  if (!response.ok) {
    discardResponse(response);
    throw new CaveRequestError(response.status, path, `cave request failed (${response.status})`);
  }
  let decoded: unknown;
  try {
    if (typeof response.text === "function") {
      decoded = JSON.parse(await response.text());
    } else if (typeof response.json === "function") {
      decoded = await response.json();
    } else {
      throw new Error("missing response decoder");
    }
  } catch {
    throw new CaveRequestError(response.status, path, "cave response was not valid JSON");
  }
  if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
    throw new CaveRequestError(response.status, path, "cave response must be a JSON object");
  }
  return decoded as Record<string, unknown>;
}

async function artifactGet(cave: Cave, artifactId: string, workflow: string, trace: TraceContext): Promise<unknown> {
  if (typeof artifactId !== "string" || artifactId.trim() === "") throw new Error("artifactId is required");
  const path = `/sdk/v1/artifacts/${encodeURIComponent(artifactId)}`;
  const response = await caveFetch(cave, `${cave.options.baseURL}${path}`, {
    method: "GET",
    headers: headers(cave, workflow, undefined, undefined, trace)
  });
  if (!response.ok) {
    discardResponse(response);
    throw new CaveRequestError(response.status, path, `cave request failed (${response.status})`);
  }

View on GitHub (pinned to 3ee70a1026)