Error and exception handling in php7

空扰寡人 提交于 2019-12-19 05:49:02

问题


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:


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



来源:https://stackoverflow.com/questions/35265717/error-and-exception-handling-in-php7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!