Is it possible to catch an exception on PHP when unserialize()
generates an error?
No, you can't catch it, unserialize()
does not throw Exception.
In case the passed string is not unserializeable, FALSE is returned and E_NOTICE is issued.
you can set a custom Exception handler to handle all errors:
function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, $errno, 0, $errfile, $errline); } set_error_handler("exception_error_handler");
A simple way is:
$ret = @unserialize($foo); if($ret === null){ //Error case }
But it isn't the most modern solution.
The best way is as mentioned before to have a custom error/exception handler (not only for this case). But depending of what you are doing it may be overkill.
Convert all PHP errors (warnings notices etc) to exceptions. Example is here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With