I try to catch exception inside a function, but it is not working.
function dbquery ($mysqli, $query){
try {
$result = mysqli_query ($mysqli, $query);
}
catch (Exception $e) {
echo "Caught exception: ".$e->getMessage();
$result = false;
}
return $result;
}
The exception is not caught in the function and an Uncaught mysqli_sql_exception is thrown when the function is called. What am I doing wrong? I dont beleave I have to make a try block around every function call…
2
Answers
You won’t be able to catch all Error could there be with the
Exception $e
. TryThrowable $e
to catch all types of Error.For more information, please refer to this question (it’s not PHP question but it’s a similar problem):
Difference between using Throwable and Exception in a try catch
As far as the official documentation is right the thrown
mysqli_sql_exception
inherits fromRuntimeException
and should be catched then, becauseRuntimeException
extends fromException
.You could at least try to catch a
Throwable
in combination with the right mysqli error reporting.mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);