experimenter
experimenter

Reputation: 778

How to handle php errors and exceptions centrally

previously in PHP 4 i created a custom error handler (below) to handle my own triggered errors and general PHP errors. But now PHP 5 introduces Exceptions i.e. I'm leveraging PDO for database manipulation and I'm not sure how to handle both general PHP errors and these Exceptions?

function errorHandler($errno, $errstr, $errfile, $errline){  
  switch ($errno) {
    case E_USER_ERROR:
    // Send an e-mail to the administrator
    error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
  break;

    case E_USER_WARNING:
    // Write the error to our log file
    error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
    break;

    case E_USER_NOTICE:
    // Write the error to our log file
  error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
    break;

    default:
    // Write the error to our log file
    error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
  break;
}

   // Don't execute PHP's internal error handler
  return TRUE;

}

Upvotes: 0

Views: 569

Answers (1)

Pekka
Pekka

Reputation: 449415

You can use set_exception_handler() to deal with uncaught exceptions in your custom function.

The "right" way, however, would be for you to try ... catch the exception when e.g. doing a query, and use your custom function to log it accordingly.

Upvotes: 1

Related Questions