SyntaxStudy
Sign Up
PHP Intermediate 4 min read

JSON Error Handling

JSON Error Handling

PHP 7.3+ added JSON_THROW_ON_ERROR flag which makes json_encode/json_decode throw a JsonException on failure instead of returning false/null silently.

Example
<?php
// PHP 7.3+: throw on error
try {
    $encoded = json_encode($data, JSON_THROW_ON_ERROR);
    $decoded = json_decode($input, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    throw new RuntimeException("JSON error: " . $e->getMessage(), 0, $e);
}

// Old approach (PHP < 7.3)
$decoded = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException(json_last_error_msg());
}
Pro Tip

Always use JSON_THROW_ON_ERROR in PHP 7.3+ — it prevents silently swallowing JSON errors.