Reputation: 780
I want to log all errors thrown by PHP in database. How can i get all errors in a variable.
In Following Code, undeclared $a has printed. but it did not catch.
$error = "";
try
{
echo $a; // not declared
}
catch(Exception $e)
{
$error = $e->getMessage();
}
Output
Notice (8): Undefined variable: a [APP\Controller\CronJobsController.php, line 71]
Upvotes: 0
Views: 92
Reputation: 86
A Notice isn't an exception, so it cannot be caught in a Try {} Catch{} block. Similarly with Warnings.
Generally a better idea to have the error_reporting level on so that they display those in your dev environment, that way you are forced to deal with those issues as you code.
However, to capture them and deal with them another way, you want to set a custom error handler. You can have your custom error handler only capture certain errors.
<?php
// set custom handler for NOTICES
// $oldHandler will allow you to reset the handler back to PHP default later
$oldHandler = set_error_handler('myErrorHandler', E_NOTICE|E_WARNING);
function myErrorHandler($errno, $errstr, $errfile, $errline) {
// log to DB in here
// $db->query("INSERT INTO error_log (errno, errstr... ) VALUES (...)");
// return false to let the error bubble up and get caught by default error handler
// return false;
// return true to tell PHP you've dealt with it
return true;
}
// YOUR SAMPLe CODE SHOULD NOW CAPTURE THE NOTICE
$error = "";
try
{
echo $a; // not declared
}
catch( \Error $e)
{
$error = $e->getMessage();
}
?>
Upvotes: 1