【问题标题】:Convert PHP 7 Error object to Exception?将 PHP 7 错误对象转换为异常?
【发布时间】:2017-05-31 10:09:30
【问题描述】:

我们多年的 PHP 代码一直在大量使用异常处理,通过 set_error_handler() 和 set_exception_handler() 将传统错误转换为异常。在为我们的一些服务器迁移到 PHP 7 之后,像这样的错误开始出现:

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

我们可以使用 \Throwable 作为类型提示,但我们的大部分代码库仍然在 PHP 5 服务器上。

有什么方法可以在这里轻松地将 Error 对象转换为 Exception 对象吗?

【问题讨论】:

  • 升级你的服务器,或者降级你的php版本

标签: php exception php-7


【解决方案1】:

您可以从方法的定义中删除类型提示,并使用get_class()instanceof 来决定要做什么。

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2010-09-23
  • 2011-06-02
  • 2017-09-19
  • 1970-01-01
  • 2010-11-01
  • 2013-03-14
  • 2016-10-07
  • 1970-01-01
相关资源
最近更新 更多