Skip to content

Instantly share code, notes, and snippets.

@mugyu
Last active December 1, 2019 05:50
Show Gist options
  • Save mugyu/b458383d66822208d7c41e45b43fc379 to your computer and use it in GitHub Desktop.
Save mugyu/b458383d66822208d7c41e45b43fc379 to your computer and use it in GitHub Desktop.
json parse error strings in PHP
<?php
class JSONErrorException extends \Exception {}
function json_error($error_code, $exceptionable = TRUE)
{
static $json_errors = NULL;
if ($json_errors === NULL)
{
$json_errors = [
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
];
if (PHP_VERSION_ID >= 50303)
{
$json_errors = array_merge($json_errors, [
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
]);
}
if (PHP_VERSION_ID >= 50500)
{
$json_errors = array_merge($json_errors, [
JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded',
JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded',
JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given',
]);
}
if (PHP_VERSION_ID >= 70000)
{
$json_errors = array_merge($json_errors, [
JSON_ERROR_INVALID_PROPERTY_NAME => 'A property name that cannot be encoded was given',
JSON_ERROR_UTF16 => 'Malformed UTF-16 characters, possibly incorrectly encoded',
]);
}
}
$error_code = (int)$error_code;
$message = 'Unknown error code';
if (isset($json_errors[$error_code]))
{
$message = $json_errors[$error_code];
}
if ($exceptionable && $error_code !== JSON_ERROR_NONE)
{
throw new JSONErrorException($message, $error_code);
}
return [$error_code, $message];
}
$json = "";
$obj = json_decode($json);
var_dump($obj);
print_r(json_error(json_last_error()));
// php 5.6.24
//
// NULL
// Array
// (
// [0] => 0
// [1] => No error has occurred
// )
// php 7.1.5
//
// NULL
//
// Fatal error: Uncaught JSONErrorException: Syntax error in /path/to/path/json_error.php:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment