Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error and exception handling in php7

Recently moved to php7. The following error occurs:

argument 1 passed to MyClass\Throwable::exceptionHandler() must be an instance of Exception, instance of Error given

And the respective class

namespace MyClass;

class Throwable
{
    public function exceptionHandler(\Exception $exception)
    {
        //logic here
    }
}

As stated in docs

most errors are now reported by throwing Error exceptions.

Does it mean that I have to provide an instance of Error or even more general Throwable to the exception handler?

like image 899
sitilge Avatar asked Feb 08 '16 09:02

sitilge


1 Answers

Errors and Exceptions both extend Throwable however Errors are not extended from Exception.

Therefore, your ExceptionHandler must accept an object of Type Throwable in order to accept Errors.

Simplest fix is this, though you may want to rename $exception to make it clear.

namespace MyClass;

class Throwable
{
    public function exceptionHandler(\Throwable $exception)
    {
        //logic here
    }
}

Note: The new Error class should not be confussed with an ErrorException which has classicly been used as a device for turning PHP 5 errors into Exception objects with symantic meaning.

http://php.net/manual/en/class.error.php

like image 143
DanielM Avatar answered Oct 13 '22 20:10

DanielM