Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch unserialize exception?

Is it possible to catch an exception on PHP when unserialize() generates an error?

like image 474
Eugene Avatar asked Oct 02 '12 05:10

Eugene


3 Answers

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"); 
like image 181
Mihai Iorga Avatar answered Sep 20 '22 16:09

Mihai Iorga


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.

like image 38
Johni Avatar answered Sep 20 '22 16:09

Johni


Convert all PHP errors (warnings notices etc) to exceptions. Example is here.

like image 36
Hemaulo Avatar answered Sep 22 '22 16:09

Hemaulo