Convert PHP 7 Object Error to Exception?

Our years of PHP code have largely used exception handling by converting traditional errors to exceptions using set_error_handler () and set_exception_handler (). After switching to PHP 7 for some of our servers, errors like this started to be pumped out:

Uncaught TypeError: Argument 1 passed to DataStellar\General\Exception_Handler::getContext() must be an instance of Exception, instance of Error given

We can use the \ Throwable as type hint, but most of our code bases are still on PHP 5 servers.

Is it possible to easily convert an Error object to an Exception object here?

+4
source share
1 answer

You can remove type hints from the method definition and use get_class()or instanceofto decide what to do.

class Exception_Handler
{
    public static function getContext($error)
    {
        if (class_exists('\\Error') && $error instanceof \Error) {
            // PHP 7 Error class
            // handle and return
        }

        if ($error instanceof \Exception) {
            // PHP Exception class (user exception in PHP7)
            // handle and return
        }

        // weird edge case
    }
}
+4
source

Source: https://habr.com/ru/post/1666918/


All Articles