简体   繁体   English

如何捕获“没有错误:未调用 PDO 构造函数”

[英]How to catch “No error: PDO constructor was not called”

how can I catch the following error: No error: PDO constructor was not called ?如何捕获以下错误: No error: PDO constructor was not called

My question is not how to solve the error, but how to catch it!我的问题不是如何解决错误,而是如何捕捉它!

I need that for a PHPUnit Testing Environment.我需要一个 PHPUnit 测试环境。

I was trying to catch it like that, but it simply doesn't work that way.我试图像那样抓住它,但它根本不起作用。

$pdo = (new \ReflectionClass(\PDO::class))->newInstanceWithoutConstructor();

try
{
    $pdo->query("SELECT * FROM table");
}
catch (ErrorException $exc)
{
    echo $exc->getTraceAsString();
}

the exact (error) message is as follows: PDO::query(): SQLSTATE[00000]: No error: PDO constructor was not called , but I am not sure, if that is even any type of PHP catchable. the exact (error) message is as follows: PDO::query(): SQLSTATE[00000]: No error: PDO constructor was not called , but I am not sure, if that is even any type of PHP catchable.

I've already checked the method pdo_raise_impl_error() [PHP 7.3.3] that is called with the mentioned error message, but I am not wise enough to anticipate what actual type of error it produces...我已经检查了使用提到的错误消息调用的方法pdo_raise_impl_error() [PHP 7.3.3],但是我没有足够的智慧来预测它产生的实际错误类型......

Can please someone give advise?可以请人给建议吗?

Not sure if it's a solution you are looking for, but you can always convert all errors to exceptions with as simple code as不确定这是否是您正在寻找的解决方案,但您始终可以使用简单的代码将所有错误转换为异常

set_error_handler(function ($level, $message, $file = '', $line = 0)
{
    throw new ErrorException($message, 0, $level, $file, $line);
});

Of course it will make a global error handler, but honestly, I believe every PHP project should have a code like this.当然它会做一个全局错误处理程序,但老实说,我相信每个 PHP 项目都应该有这样的代码。

Or at least you can call this handler only temporarily或者至少你只能暂时调用这个处理程序

I now use the following code fore my test.我现在在我的测试中使用以下代码。 please check the first and the last line of code especially.请特别检查第一行和最后一行代码。

thanks to @YourCommonSense!感谢@YourCommonSense!

set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline) {
    throw new ErrorException($errstr, $errno, E_ERROR, $errfile, $errline);
});

$this->expectException(ErrorException::class);
$this->expectExceptionMessage("SQLSTATE[00000]: No error: PDO constructor was not called");

/* @var $pdo PDO */
$pdo = (new ReflectionClass(PDO::class))->newInstanceWithoutConstructor();
$pdo->query("SELECT * FROM table"); // triggers the error.

restore_error_handler();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM