{"record":{"id":"3e635a90d5f90f1e","repo":"affaan-m/ECC","slug":"failed-to-parse-data-data","errorCode":null,"errorMessage":"Failed to parse data: {data}","messagePattern":"Failed to parse data: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"skills/python-patterns/SKILL.md","lineNumber":172,"sourceCode":"\n# Bad: Bare except\ndef load_config(path: str) -> Config:\n    try:\n        with open(path) as f:\n            return Config.from_json(f.read())\n    except:\n        return None  # Silent failure!\n```\n\n### Exception Chaining\n\n```python\ndef process_data(data: str) -> Result:\n    try:\n        parsed = json.loads(data)\n    except json.JSONDecodeError as e:\n        # Chain exceptions to preserve the traceback\n        raise ValueError(f\"Failed to parse data: {data}\") from e\n```\n\n### Custom Exception Hierarchy\n\n```python\nclass AppError(Exception):\n    \"\"\"Base exception for all application errors.\"\"\"\n    pass\n\nclass ValidationError(AppError):\n    \"\"\"Raised when input validation fails.\"\"\"\n    pass\n\nclass NotFoundError(AppError):\n    \"\"\"Raised when a requested resource is not found.\"\"\"\n    pass\n\n# Usage","sourceCodeStart":154,"sourceCodeEnd":190,"githubUrl":"https://github.com/affaan-m/ECC/blob/01e15490f04e29cfefe3896951f43db46994d8ee/skills/python-patterns/SKILL.md#L154-L190","documentation":"A ValueError raised from process_data() when json.loads(data) throws json.JSONDecodeError. The input string could not be parsed as JSON. The original exception is chained via `raise ... from e` so the underlying decode failure is not lost.","triggerScenarios":"Calling process_data(data) with a string that is not valid JSON — empty string, HTML error page returned instead of JSON, truncated payload, or data already deserialized (a dict passed where a string was expected).","commonSituations":"Reading a response body that turned out to be an HTML 502 page; receiving a streaming chunk rather than a complete message; double-decoding (passing already-parsed dict to json.loads); locale-dependent number formatting in serialized data.","solutions":["Log `repr(data[:200])` before parsing to see exactly what was fed to json.loads.","Confirm the upstream source actually returns JSON (check Content-Type header and status code before parsing).","If data may arrive in chunks, buffer until a complete JSON document is available before parsing.","Guard with a type check: if isinstance(data, (dict, list)): return data to avoid re-parsing already-deserialized input."],"exampleFix":"# before\nparsed = json.loads(data)\n\n# after: verify the source is JSON before parsing\nif not isinstance(data, str):\n    return data  # already deserialized\nparsed = json.loads(data)","handlingStrategy":"validation","validationCode":"def safe_json_loads(data):\n    if isinstance(data, (dict, list)):\n        return data\n    if not isinstance(data, str):\n        raise TypeError(f\"expected str, got {type(data).__name__}\")\n    try:\n        return json.loads(data)\n    except json.JSONDecodeError as e:\n        raise ValueError(f\"Failed to parse data: {data[:120]!r}\") from e","typeGuard":"from typing import Any\ndef is_json_string(s: Any) -> bool:\n    if not isinstance(s, str):\n        return False\n    try:\n        json.loads(s)\n        return True\n    except json.JSONDecodeError:\n        return False","tryCatchPattern":"try:\n    parsed = json.loads(data)\nexcept json.JSONDecodeError as e:\n    log.warning(\"unparseable payload (%d bytes): %s\", len(data), e)\n    raise ValueError(f\"Failed to parse data\") from e","preventionTips":["Check the upstream Content-Type and status code before parsing response bodies.","Buffer streamed input until a full JSON document is available.","Log repr(data[:200]) on parse failure for quick diagnosis."],"tags":["python","json","parsing","validation"],"backgroundTag":null,"analyzedSha":"01e15490f04e29cfefe3896951f43db46994d8ee","analyzedAt":"2026-08-13T00:31:08.655Z","schemaVersion":2},"datasetVersion":"2026-08-13T04:17:16.726Z"}