JSON error handling
Learn to catch JSON errors with json_last_error() and json_last_error_msg().
Catch errors with last_error
When the decode function receives an invalid string, it returns null and silently sets an error flag. You read this error as a code with last_error, and as a short message with last_error_msg.
If there is no error, last_error returns the ERROR_NONE constant. On a syntax error, ERROR_SYNTAX is returned and the message is Syntax error. So checking the state after decoding is a good habit.
Throw exceptions with THROW_ON_ERROR
In the traditional approach, you check the error with last_error. A modern alternative is the THROW_ON_ERROR flag. When passed to decode or encode, this flag makes the function throw an exception on error.
With this, you catch the error in one place using a try/catch block. You pick one approach: either check last_error after each call, or use THROW_ON_ERROR with try/catch.
Exercise Print the error message of an invalid string
The $text variable holds an invalid string. Decode it with the decode function, then print the error message with last_error_msg.
Show example solution
Decode $text, then call last_error_msg() with echo.
Example solution:
decode($text, true);
echo last_error_msg();
Test yourself
-
Match error functions and constants
- json_last_error
- returns the error code
- json_last_error_msg
- returns the error message
- ERROR_NONE
- no error state
- ERROR_SYNTAX
- syntax error
-
Which function returns the error message as text?
- the encode function
- the decode function
- the last_error function
- the last_error_msg function
Show answer
the last_error_msg function — Correct. The last_error_msg function returns the error message as a short text.
-
Check the error code
$text = '{invalid}'; decode($text, true); if (____ !== ERROR_NONE) { echo last_error_msg(); }Show answer
$text = '{invalid}'; decode($text, true); if (last_error() !== ERROR_NONE) { echo last_error_msg(); }