{"record":{"id":"49783e9374a5f378","repo":"phalcon/cphalcon","slug":"json-last-error-msg-49783e","errorCode":null,"errorMessage":"json_last_error_msg()","messagePattern":"json_last_error_msg\\(\\)","errorType":"exception","errorClass":"\\JsonException","httpStatus":null,"severity":"error","filePath":"phalcon/Traits/Support/Helper/Json/EncodeTrait.zep","lineNumber":55,"sourceCode":"        var encoded, error, message;\n\n        /**\n         * Need to clear the json_last_error() before the code below\n         */\n        let encoded = json_encode(null),\n            encoded = json_encode(data, options, depth),\n            error   = json_last_error(),\n            message = json_last_error_msg();\n\n        /**\n         * When JSON_THROW_ON_ERROR is set, json_encode() has already raised a\n         * native \\JsonException above; otherwise the error is surfaced the\n         * same way here.\n         */\n        if (JSON_ERROR_NONE !== error) {\n            json_encode(null);\n\n            throw new \\JsonException(message, error);\n        }\n\n        return (string) encoded;\n    }\n}\n","sourceCodeStart":37,"sourceCodeEnd":61,"githubUrl":"https://github.com/phalcon/cphalcon/blob/b7419de9cd0a8a3f48441ead84c9f8415d463e25/phalcon/Traits/Support/Helper/Json/EncodeTrait.zep#L37-L61","documentation":"The JSON encode helper (Phalcon\\Support\\Helper\\Json\\Encode, via EncodeTrait::toEncode) wraps json_encode and converts failures into a native \\JsonException carrying json_last_error_msg() — typical messages: 'Double INF or NaN did not resolve to a finite number', 'Recursion detected', 'Malformed UTF-8 characters, possibly incorrectly encoded' (phalcon/Traits/Support/Helper/Json/EncodeTrait.zep:55).","triggerScenarios":"Encode::__invoke($data) on structures containing INF/NAN floats, recursive arrays/objects, resources, or strings with invalid UTF-8 (binary from a DB, latin1 data read as UTF-8).","commonSituations":"Encoding computed floats that hit division-by-zero yielding INF; cache layers storing layered arrays that reference themselves; DB rows in the wrong charset; binary blobs accidentally placed in an API payload.","solutions":["Sanitize first: normalize INF/NAN to 0/null, and re-encode strings with mb_convert_encoding($s, 'UTF-8', 'UTF-8') or filter invalid bytes.","Pass JSON_INVALID_UTF8_SUBSTITUTE in the options bitmask to substitute bad bytes instead of failing.","Catch \\JsonException at the boundary and degrade gracefully (skip the cache entry, return an error payload) instead of a 500."],"exampleFix":"// before\n$json = (new Encode())->__invoke(['score' => log(0)]); // -INF -> JsonException\n\n// after\n$payload = ['score' => is_finite($score) ? $score : 0];\n$json    = (new Encode())->__invoke($payload, JSON_INVALID_UTF8_SUBSTITUTE);","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"try {\n    $json = (new Encode())->__invoke($payload, JSON_INVALID_UTF8_SUBSTITUTE);\n} catch (\\JsonException $e) {\n    $logger->error('JSON encode failed: ' . $e->getMessage());\n    $json = null; // skip the cache entry / return error payload\n}","preventionTips":["Normalize floats (is_finite) before encoding to avoid INF/NAN failures.","Add JSON_INVALID_UTF8_SUBSTITUTE when data may contain legacy-charset bytes from a DB.","Break circular references before caching layered structures; catch \\JsonException at the cache/API boundary."],"tags":["phalcon","json","encode","jsonexception","utf8"],"backgroundTag":"json-encode-error","analyzedSha":"b7419de9cd0a8a3f48441ead84c9f8415d463e25","analyzedAt":"2026-08-21T06:21:18.811Z","schemaVersion":2},"datasetVersion":"2026-08-21T11:28:35.574Z"}