14

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?

1

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

3 Comments

Both Errors and Exceptions are children of Throwable; ok, if I switched to your solution what could be the difference between Error and Exception? And set_exception_handler now provides object of Error ? Then what are Exception meant for and how are they handled?
If you want to specifically handle an Exception and not an Error you could always do if ($throwable instanceof \Exception) { ... }. I'm curious as to why you'd want to deal with them differently at that point though? :)
you're right. This would be the preferable solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.