{"record":{"id":"17f4006e964cd897","repo":"Stirling-Tools/Stirling-PDF","slug":"failed-to-parse-pdf-json-document","errorCode":null,"errorMessage":"Failed to parse PDF JSON document","messagePattern":"Failed to parse PDF JSON document","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx","lineNumber":854,"sourceCode":"        } else {\n          const content = await file.text();\n          const docResult = JSON.parse(content) as PdfJsonDocument;\n          parsed = {\n            ...docResult,\n            pages: docResult.pages ?? [],\n          };\n          shouldUseLazyMode = false;\n          pendingJobId = null;\n        }\n\n        setConversionProgress(null);\n\n        if (loadRequestIdRef.current !== requestId) {\n          return;\n        }\n\n        if (!parsed) {\n          throw new Error(\"Failed to parse PDF JSON document\");\n        }\n\n        console.log(\n          `[PdfTextEditor] Document loaded. Lazy image mode: ${shouldUseLazyMode}, Pages: ${parsed.pages?.length || 0}`,\n        );\n\n        if (isPdf) {\n          initializePdfPreview(file);\n        } else {\n          clearPdfPreview();\n        }\n\n        setLoadedDocument(parsed);\n        resetToDocument(parsed, groupingMode);\n        setIsLazyMode(shouldUseLazyMode);\n        const newJobId = shouldUseLazyMode ? pendingJobId : null;\n        setCachedJobId(newJobId);\n        cachedJobIdRef.current = newJobId;","sourceCodeStart":836,"sourceCodeEnd":872,"githubUrl":"https://github.com/Stirling-Tools/Stirling-PDF/blob/9ef20dcab80b85041912f045e17a6aea1d08f969/frontend/editor/src/core/tools/pdfTextEditor/PdfTextEditor.tsx#L836-L872","documentation":"Thrown as the final defensive guard after both the async and synchronous conversion paths. If parsed is still null/undefined after all code paths (async polling, synchronous JSON parsing), this fires. It indicates neither path successfully produced a PdfJsonDocument, which should be logically impossible if the code above executed correctly.","triggerScenarios":"A code path that should set parsed was skipped due to an early return or conditional. The loadRequestIdRef check returned early but then fell through. An empty file (zero bytes) was passed, causing file.text() to return an empty string that JSON.parse handled unexpectedly.","commonSituations":"Empty or invalid file input. Logic regression after refactoring the conversion flow. Unhandled edge case where isPdf is false but the file is also not valid JSON.","solutions":["Add detailed logging of all local variables (isPdf, requestId match, parsed value) before this throw.","Validate the input file is non-empty and is either a valid PDF or valid JSON before entering the conversion flow.","If reproducible, report as a bug — this guard should be unreachable in normal operation.","Check that loadRequestIdRef.current === requestId hasn't changed (stale request) before reaching this point."],"exampleFix":"// before\nif (!parsed) {\n  throw new Error(\"Failed to parse PDF JSON document\");\n}\n\n// after\nif (!parsed) {\n  console.error(\"Parse failed. isPdf:\", isPdf, \"requestId match:\", loadRequestIdRef.current === requestId);\n  throw new Error(\n    isPdf\n      ? \"Failed to convert PDF. The file may be corrupted or unsupported.\"\n      : \"Failed to parse JSON document. The file may not be a valid PDF text editor file.\"\n  );\n}","handlingStrategy":"try-catch","validationCode":"// Validate input file before conversion\nif (!file || file.size === 0) {\n  throw new Error('Cannot convert an empty file.');\n}\nconst isPdf = file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf');\nif (!isPdf && !file.name.toLowerCase().endsWith('.json')) {\n  throw new Error('File must be a PDF or a PDF text editor JSON file.');\n}","typeGuard":"function isParsedDocument(value: unknown): value is PdfJsonDocument {\n  return value !== null && value !== undefined && typeof value === 'object' &&\n    Array.isArray((value as any).pages);\n}","tryCatchPattern":"try {\n  // ... all conversion logic ...\n} catch (error) {\n  if (error instanceof Error && error.message === 'Failed to parse PDF JSON document') {\n    setErrorMessage('The document could not be parsed. It may be corrupted or in an unsupported format.');\n  } else {\n    throw error;\n  }\n}","preventionTips":["Validate input file is non-empty and is a supported format before conversion.","Add comprehensive logging before this defensive guard.","Treat reaching this guard as a bug — it should be unreachable in normal operation.","Check that the requestId guard (loadRequestIdRef) hasn't caused a silent early return."],"tags":["pdf-text-editor","parsing","defensive-guard","conversion","unreachable"],"backgroundTag":null,"analyzedSha":"9ef20dcab80b85041912f045e17a6aea1d08f969","analyzedAt":"2026-08-13T22:11:39.827Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}