I'm trying to make an error handler to convert errors to JSON for my ajax requests. I've got a DB class which handles all MySql queries and which calls the following function when errors happens:
private function halt($msg)
{
$this->Error = @mysqli_error($this->Link_ID);
$this->Errno = @mysqli_errno($this->Link_ID);
if ($this->throw = true) {
throw new \Exception("Mysql Error: $msg. Error: $this->Errno ($this->Error)");
} else if ($this->Halt_On_Error == "no") {
return;
}
$this->haltmsg($msg);
if ($this->Halt_On_Error != "report") {
die("Session halted.");
}
}
In my ajax script, I've got some functions like this one:
private function add()
{
$this->changeErrorCatcher(ON);
try {
$obj = $this->mgr->getEmptyObject();
foreach ($this->fields as $field) {
if (!$this->form->vide($field) && $field != "id") {
$name = "set" . ucfirst($field);
$obj->$name($this->form->get($field));
}
}
$this->mgr->create($obj);
Ajax::Response(AJX_ACC, "Ok", $obj->getId());
} catch (\Throwable $e) {
Ajax::Response(AJX_ERR, $e->getMessage(), $e);
}
}
changeErrorCatcher function:
private function changeErrorCatcher(bool $onOff)
{
if ($onOff) {
set_error_handler(function ($errno, $errstr) {
throw new \Exception($errstr, $errno);
}, E_ALL | E_ERROR | E_STRICT | E_USER_ERROR);
} else {
restore_error_handler();
}
}
My problem is that the try/catch block in the add() function is not working: the line "$this->mgr->create($obj);" calls my DB class, so the halt() function is called when an error occurs and an Exception is thrown, but the catch block is never launched, and the text of the Exception is sent as ajax result (Making my JS fail parsing JSON)
I already tried solutions proposed here but nothing works (\Exceptions instead of Exception (even \Throwable does not work), disabling XDEBUG, changing error handler)
EDIT: I tried changing this in halt function:
if ($this->throw = true) {
throw new \Exception("Mysql Error: $msg. Error: $this->Errno ($this->Error)");
}
Into:
if ($this->throw = true) {
try {
throw new \Exception("Mysql Error: $msg. Error: $this->Errno ($this->Error)");
} catch (\Exception $e) {
throw new \Exception("Mysql Error: $msg. Error: $this->Errno ($this->Error) ".$e->getTraceAsString());
}
}
Now I've got the stack trace in my ajax result, so the first exception is well catched but not the second... The stack trace shows me it is the line "$this->mgr->create($obj);" which throws exception.