php7中的错误和异常处理 [英] Error and exception handling in php7

查看:288
本文介绍了php7中的错误和异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近移到了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

以及相应类

namespace MyClass;

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

文档


现在大多数错误是通过抛出Error来报告的

most errors are now reported by throwing Error exceptions.

这是否意味着我必须提供 Error 的实例甚至对异常处理程序更通用的 Throwable

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

推荐答案

错误异常都扩展了 Throwable ,但是错误没有从例外

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

因此,您的ExceptionHandler必须接受 Throwable 类型的对象,以便接受 Errors

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

最简单的解决方法是这个,尽管您可能想重命名$ exception以使其清晰。

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
    }
}

注意:新的 Error 类不应与 ErrorException 混淆,该错误通常用作将PHP 5错误转换为 Exception 对象的设备

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

这篇关于php7中的错误和异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆