{"record":{"id":"3f29e5ecded948dc","repo":"jackwener/OpenCLI","slug":"wikipedia-returned-malformed-json-error-messag","errorCode":null,"errorMessage":"wikipedia returned malformed JSON: ${error?.message || error}","messagePattern":"wikipedia returned malformed JSON: (.+?)","errorType":"exception","errorClass":"CommandExecutionError","httpStatus":null,"severity":"error","filePath":"clis/wikipedia/page.js","lineNumber":69,"sourceCode":"        let resp;\n        try {\n            resp = await fetch(url, {\n                headers: {\n                    'User-Agent': 'opencli/1.0 (+https://github.com/jackwener/opencli)',\n                    'Accept': 'application/json',\n                },\n            });\n        } catch (error) {\n            throw new CommandExecutionError(`wikipedia page request failed: ${error?.message || error}`);\n        }\n        if (!resp.ok) {\n            throw new CommandExecutionError(`wikipedia page failed: HTTP ${resp.status}`);\n        }\n        let data;\n        try {\n            data = await resp.json();\n        } catch (error) {\n            throw new CommandExecutionError(`wikipedia returned malformed JSON: ${error?.message || error}`);\n        }\n        if (data?.error) {\n            throw new CommandExecutionError(`wikipedia API error: ${data.error.info || data.error.code}`);\n        }\n        const pages = Array.isArray(data?.query?.pages) ? data.query.pages : [];\n        const page = pages[0];\n        if (!page || page.missing) {\n            throw new EmptyResultError('wikipedia page', `No article \"${title}\" on ${lang}.wikipedia.org. Try \\`opencli wikipedia search\\` first.`);\n        }\n        const fullExtract = String(page.extract ?? '');\n        if (!fullExtract.trim()) {\n            throw new EmptyResultError('wikipedia page', `Article \"${page.title}\" exists but has no plain-text extract (likely a disambiguation/redirect page).`);\n        }\n        const allParas = fullExtract.split(/\\n{2,}/).map(s => s.trim()).filter(Boolean);\n        const paras = paragraphsCap > 0 ? allParas.slice(0, paragraphsCap) : allParas;\n\n        return [{\n            title: page.title,","sourceCodeStart":51,"sourceCodeEnd":87,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/wikipedia/page.js#L51-L87","documentation":"After a 2xx response, page.js parses the body with resp.json(). If parsing fails — the body is not valid JSON (HTML error/interstitial page, truncated stream, wrong content type) — it throws a CommandExecutionError with the parse error message.","triggerScenarios":"A proxy, captive portal, or anti-bot layer returning an HTML page with status 200; the response stream being cut off mid-body; hitting a non-API URL that serves HTML while still reporting success.","commonSituations":"Corporate networks or hotel Wi-Fi injecting login pages; aggressive caching middleboxes serving stale HTML; malformed responses during partial Wikimedia incidents.","solutions":["Capture and inspect the raw response text to see what was actually returned","Retry — truncation is often transient","Bypass proxies/VPNs or fix captive-portal connectivity","Confirm the request targets <lang>.wikipedia.org/w/api.php with format=json"],"exampleFix":"// before\nconst data = await resp.json();\n// after\nconst text = await resp.text();\nlet data;\ntry { data = JSON.parse(text); }\ncatch { throw new Error(`unexpected body: ${text.slice(0, 200)}`); }","handlingStrategy":"try-catch","validationCode":null,"typeGuard":"function looksLikeApiJson(v) { return v !== null && typeof v === 'object' && ('query' in v || 'error' in v); }","tryCatchPattern":"try {\n  return await pageCommand(args);\n} catch (err) {\n  if (err instanceof CommandExecutionError && err.message.includes('malformed JSON')) {\n    console.error('non-JSON body from wikipedia — likely proxy/interstitial; retry');\n    throw err;\n  }\n  throw err;\n}","preventionTips":["Bypass proxies/captive portals when calling the API","Retry transient truncations","Verify api.php + format=json is requested (the CLI already does this)","Check the raw body when errors persist to spot injected HTML"],"tags":["json","parse-error","wikipedia","network"],"backgroundTag":"malformed-json-response","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}