我们多年来的 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/