Try/catch 'Call to a member function query() on null' 错误

Try/catch 'Call to a member function query() on null' error

我有一个 SQL 查询 ($query),它是我根据用户的选择动态创建的(我已经对用户输入进行了清理,因此不存在 SQL 注入问题).但是有时查询 returns a PHP Fatal error 所以我想将所有变量输出到一个文件所以做一些挖掘。

我的代码是:

try {
    $results = $db->query($query);
} catch (Exception $e) {
    $all_vars = get_defined_vars();
    file_put_contents('query_problems.txt',date('Y-m-d H:i:s') . print_r($all_vars, True),FILE_APPEND);
}

但是我仍然收到错误消息

Uncaught Error: Call to a member function query() on null

它指向的线是我 运行 $db->query($query).

我做错了什么?我如何捕获此错误?

问题是您正在捕捉 Exception, not an Error (that is being throw). If you want to catch both (exceptions and errors), you should use Throwable

try
{
   // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
   // Executed only in PHP 7, will not match in PHP 5
}

正如文档中所说:

As the Error hierarchy does not inherit from Exception, code that uses catch (Exception $e) { ... } blocks to handle uncaught exceptions in PHP 5 will find that these Errors are not caught by these blocks. Either a catch (Error $e) { ... } block or a set_exception_handler() handler is required.