JSON_THROW_ON_ERROR
When something goes wrong, the json_encode()
function returns false
by default:
var_dump(json_encode('\x80'));
Executing the code shown above will print the output shown below:
bool(false)
This is not very helpful and to make things worse, if you want to
know what went wrong, you have to call
json_last_error()
which returns an error code. And then
you need to know what that error code means.
To make all of this easier, PHP 7.3 introduced the
JSON_THROW_ON_ERROR
option:
try {
$json = json_encode('\x80', JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
print $e->getMessage();
}
Executing the code shown above will print the output shown below:
Malformed UTF-8 characters, possibly incorrectly encoded
By default, the json_decode()
function handles
errors similarly to json_encode()
– with the difference
that it returns NULL
when something goes wrong:
var_dump(json_decode('{'));
Executing the code shown above will print the output shown below:
NULL
The JSON_THROW_ON_ERROR
option can be used with
json_decode()
, too:
try {
$variable = json_decode('{', false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
print $e->getMessage();
}
Executing the code shown above will print the output shown below:
Syntax error