{"record":{"id":"8a0ae92d389da001","repo":"JuliusBrussee/caveman","slug":"cave-response-was-not-valid-json","errorCode":null,"errorMessage":"cave response was not valid JSON","messagePattern":"cave response was not valid JSON","errorType":"http","errorClass":"CaveRequestError","httpStatus":null,"severity":"error","filePath":"packages/sdk/typescript/src/index.ts","lineNumber":2135,"sourceCode":"    headers: { ...headers(cave, workflow ?? cave.options.defaultWorkflow ?? \"unlabeled-workflow\", undefined, undefined, trace), ...extraHeaders }\n  };\n  if (body !== undefined) init.body = JSON.stringify(body);\n  const response = await caveFetch(cave, `${cave.options.baseURL}${path}`, init);\n  if (!response.ok) {\n    discardResponse(response);\n    throw new CaveRequestError(response.status, path, `cave request failed (${response.status})`);\n  }\n  let decoded: unknown;\n  try {\n    if (typeof response.text === \"function\") {\n      decoded = JSON.parse(await response.text());\n    } else if (typeof response.json === \"function\") {\n      decoded = await response.json();\n    } else {\n      throw new Error(\"missing response decoder\");\n    }\n  } catch {\n    throw new CaveRequestError(response.status, path, \"cave response was not valid JSON\");\n  }\n  if (decoded === null || typeof decoded !== \"object\" || Array.isArray(decoded)) {\n    throw new CaveRequestError(response.status, path, \"cave response must be a JSON object\");\n  }\n  return decoded as Record<string, unknown>;\n}\n\nasync function artifactGet(cave: Cave, artifactId: string, workflow: string, trace: TraceContext): Promise<unknown> {\n  if (typeof artifactId !== \"string\" || artifactId.trim() === \"\") throw new Error(\"artifactId is required\");\n  const path = `/sdk/v1/artifacts/${encodeURIComponent(artifactId)}`;\n  const response = await caveFetch(cave, `${cave.options.baseURL}${path}`, {\n    method: \"GET\",\n    headers: headers(cave, workflow, undefined, undefined, trace)\n  });\n  if (!response.ok) {\n    discardResponse(response);\n    throw new CaveRequestError(response.status, path, `cave request failed (${response.status})`);\n  }","sourceCodeStart":2117,"sourceCodeEnd":2153,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/sdk/typescript/src/index.ts#L2117-L2153","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Log err.status and err.path, then curl the same URL to inspect the raw body being returned","Verify baseURL is the Cave API root, not a proxy, gateway, or marketing domain","Check intermediary infrastructure (nginx, Cloudflare, corporate proxy) for HTML error pages or body rewriting","Retry on transient gateway errors (502/503/504) with exponential backoff"],"exampleFix":"// before\nconst data = await sdk.getStats(); // CaveRequestError: cave response was not valid JSON\n// after\ntry {\n  const data = await sdk.getStats();\n} catch (err) {\n  if (err instanceof CaveRequestError && /not valid JSON/.test(err.message)) {\n    console.error(`non-JSON body from ${err.path} (status ${err.status}) — check gateway/proxy`);\n  }\n  throw err;\n}","handlingStrategy":"try-catch","validationCode":"// pre-flight: const res = await fetch(baseURL + '/sdk/v1/health'); await res.json(); // throws if non-JSON","typeGuard":null,"tryCatchPattern":"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; }","preventionTips":["Point baseURL strictly at the Cave API origin, never at a proxy/landing page","Alert on gateway 502/503 HTML pages by probing a health endpoint","Set a reasonable timeout so truncated bodies are detected early","Retry idempotent calls on transient gateway failures"],"tags":["json","http","network","proxy"],"backgroundTag":"invalid-json-response","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}