Monday 10 June 2019

php - Uncaught Error in try catch block




I am trying to write "universal" function to execute SQL query and return JSON and handle error within. And during process there is something I don't understand - why try catch block doesn't handle error. (Later I will improve logic - question is NOT about that, but purely about error handling).



Here is my code:




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);
}
}


How I call this function:



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



This gives following expected error:



Uncaught Error: Call to a member function fetch_assoc() on boolean in ...


What I don't understand why catch block is not executed in this case?


Answer



In php errors are not exceptions. If you want to catch them, write your own error_handler. http://php.net/manual/en/function.set-error-handler.php



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...