php - 将 PHP 7 错误对象转换为异常?

标签 php exception php-7

我们多年来的 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 对象吗?

最佳答案

您可以从方法的定义中删除类型提示,并使用 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
    }
}

关于php - 将 PHP 7 错误对象转换为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41678620/

相关文章:

javascript - 关于谷歌标签管理器

android - 消费者关闭输入 channel 或发生错误。事件=0x8

c++ - 为什么抛出局部变量调用 moves 构造函数?

oracle - 我可以使用 PHP7 提高 oci8 的性能吗?

PHP 可迭代到数组或可遍历

javascript - jQuery $.getJSON 不返回数据

php - 提交表单后如何在后台运行 PHP 脚本?

Maven 故障安全插件 - SurefireBooterForkException : There was an error in the forked process (TypeNotPresentExceptionProxy)

php - 自 PHP 7.0.0 起不推荐使用 password_hash?

javascript - 如何使用 Invisible reCaptcha 保护 jquery 按钮?