0

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]
Hardeep Singh
  • 743
  • 1
  • 8
  • 18
  • when you print `$error`, what do you get? – Rotimi May 05 '17 at 08:07
  • I think this can help: [Outputting all PHP errors to database not error_log](http://stackoverflow.com/questions/2911094/outputting-all-php-errors-to-database-not-error-log) – Spoody May 05 '17 at 08:08
  • did you use [`set_error_handler()`](https://www.w3schools.com/php/func_error_set_error_handler.asp)? – Bagus Tesa May 05 '17 at 08:08

1 Answers1

1

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

?>
timswann
  • 76
  • 1
  • 5