try catch 块中未捕获的错误

lap*_*nis 5 php mysql

我正在尝试编写“通用”函数来执行 SQL 查询并返回 JSON 并处理其中的错误。在处理过程中,有一些我不明白的事情 - 为什么 try catch 块不处理错误。(稍后我将改进逻辑 - 问题与此无关,而纯粹与错误处理有关)。

这是我的代码:

public
function sqlToJSON($query, $type = array(), $params = array())
{
    try {
        $data = array();
        $stmt = $this->mysqli->prepare($query);
        if (count($type) > 0 && count($params) > 0) {
            call_user_func_array(array($stmt, "bind_param"), array_merge(array($type), $params));
        }
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        $stmt->free_result();
        $stmt->close();
        return array('result' => 'success', 'error' => null, 'data' => $data);
    } catch (Exception $e) {
        $this->sqlError = 'Caught exception: ' . $e->getMessage();
        return array('result' => 'failed', 'error' => $e->getMessage(), 'data' => null);
    }
}
Run Code Online (Sandbox Code Playgroud)

我如何调用这个函数:

    $q = 'INSERT INTO receivers (receiver_name, owner) VALUES (UPPER(?), ?)';
    $params = array(&$receiverName, &$clientEmail);
    $this->sqlToJSON($q, 'ss', $params);
Run Code Online (Sandbox Code Playgroud)

这给出了以下预期错误:

Uncaught Error: Call to a member function fetch_assoc() on boolean in ...
Run Code Online (Sandbox Code Playgroud)

我不明白为什么在这种情况下不执行 catch 块?

小智 7

在 php 中,错误也不例外。如果你想捕获它们,请编写你自己的 error_handler。http://php.net/manual/en/function.set-error-handler.php