{"record":{"id":"09c0b2f10f6b2328","repo":"paperclipai/paperclip","slug":"api-error-response-status-bytes-tostring-ut","errorCode":null,"errorMessage":"API error ${response.status}: ${bytes.toString(\"utf8\")}","messagePattern":"API error (.+?): (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"cli/src/commands/client/workspace.ts","lineNumber":140,"sourceCode":"    { includeCompany: false },\n  );\n}\n\nfunction addBinaryCompanyGet(parent: Command, name: string, description: string, path: string): void {\n  addCommonClientOptions(\n    parent\n      .command(name)\n      .description(description)\n      .option(\"-C, --company-id <id>\", \"Company ID\")\n      .option(\"--out <path>\", \"Write output to file\")\n      .action(async (opts: OrgOutputOptions) => {\n        try {\n          const ctx = resolveCommandContext(opts, { requireCompany: true });\n          const response = await fetch(buildApiUrl(ctx.api.apiBase, `${apiPath`/api/companies/${ctx.companyId}`}/${path}`), {\n            headers: ctx.api.apiKey ? { authorization: `Bearer ${ctx.api.apiKey}` } : undefined,\n          });\n          const bytes = Buffer.from(await response.arrayBuffer());\n          if (!response.ok) throw new Error(`API error ${response.status}: ${bytes.toString(\"utf8\")}`);\n          if (opts.out) {\n            const { writeFile } = await import(\"node:fs/promises\");\n            await writeFile(opts.out, bytes);\n            printOutput({ out: opts.out, bytes: bytes.byteLength }, { json: ctx.json });\n            return;\n          }\n          process.stdout.write(bytes);\n        } catch (err) {\n          handleCommandError(err);\n        }\n      }),\n    { includeCompany: false },\n  );\n}\n\nfunction addCompanyPostJson(parent: Command, name: string, description: string, path: string): void {\n  addCommonClientOptions(\n    parent","sourceCodeStart":122,"sourceCodeEnd":158,"githubUrl":"https://github.com/paperclipai/paperclip/blob/67001ec6eb96ae601aa27bc91d9b2415d665334a/cli/src/commands/client/workspace.ts#L122-L158","documentation":"Thrown by the workspace org-output command (workspace.ts:140) when fetch() against /api/companies/{id}/{path} returns a non-OK HTTP status. The error message embeds the HTTP status code and the raw response body as UTF-8 for diagnostics.","triggerScenarios":"Any non-2xx response from the company export endpoint: 401/403 (auth), 404 (wrong company or path), 500 (server error), or network-layer non-OK. Uses raw fetch, not the API client, so auth comes from ctx.api.apiKey as a Bearer header.","commonSituations":"Missing or expired API key, wrong --company-id, base URL pointing at the wrong host, or a server-side failure during export.","solutions":["Read the embedded status and body text: 401/403 → fix the API key; 404 → fix the company/path; 5xx → check server logs.","Confirm the API base URL and that ctx.api.apiKey is set (PAPERCLIP_API_KEY or login).","Verify --company-id exists and the user has access.","Retry once for transient 5xx; if persistent, inspect server logs."],"exampleFix":"// before: 401 Unauthorized\n// ensure API key is set\nexport PAPERCLIP_API_KEY=...\npaperclipai ... workspace org-output --company-id X","handlingStrategy":"try-catch","validationCode":"async function ensureCompanyExportOk(baseUrl: string, apiKey: string | undefined, companyId: string, path: string) {\n  const res = await fetch(`${baseUrl}/api/companies/${companyId}/${path}`, {\n    headers: apiKey ? { authorization: `Bearer ${apiKey}` } : undefined,\n  });\n  if (!res.ok) {\n    const body = await res.text();\n    throw new Error(`Pre-check failed: ${res.status} ${body}`);\n  }\n  return res;\n}","typeGuard":"function isOkResponse(res: Response): boolean {\n  return res.ok;\n}","tryCatchPattern":"try {\n  const response = await fetch(url, { headers });\n  const bytes = Buffer.from(await response.arrayBuffer());\n  if (!response.ok) throw new Error(`API error ${response.status}: ${bytes.toString(\"utf8\")}`);\n} catch (err) {\n  if (err instanceof Error && err.message.startsWith(\"API error 401\")) {\n    // refresh API key, then retry once\n  } else if (err instanceof Error && err.message.startsWith(\"API error 5\")) {\n    // transient; retry with backoff\n  } else {\n    throw err;\n  }\n}","preventionTips":["Ensure PAPERCLIP_API_KEY is set and valid before running export commands.","Confirm the API base URL and company id.","Inspect the embedded status and body to classify the failure."],"tags":["cli","http","workspace","auth","diagnostics"],"backgroundTag":null,"analyzedSha":"67001ec6eb96ae601aa27bc91d9b2415d665334a","analyzedAt":"2026-08-12T12:05:45.408Z","schemaVersion":2},"datasetVersion":"2026-08-12T18:17:37.767Z"}