Can json_encode trigger a catch block?
No but you can check it's return value in a function and throw an exception when something goes wrong. You can also use json_last_error
to get details on the error
Example:
function my_json_encode($data) {
if( json_encode($data) === false ) {
throw new Exception( json_last_error() );
}
}
try {
my_json_encode($data);
}
catch(Exception $e ) {
// do something
}
I do find it highly annoying that to get the actual error message you have to check a list of constants that is returned from json_last_error()
. In the past I've used a switch / case statement to make that happen but you could throw different exceptions depending on the error.