views:

25

answers:

1

Hi

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;

}

A: 

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.

Pekka
Hi Pekka, I'm using try/catch around my queries already - but how would i leverage the same custom function im using to handle errors?try { $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password); /*** echo a message saying we have connected ***/ echo 'Connected to database'; }catch(PDOException $e) { echo $e->getMessage(); }
@mindfriction you could trigger an error to get your custom function - an exceptions purist would probably cringe at the thought, but I can't really see anything structurally wrong with it - you're logging the message either way.
Pekka
JUst had a thought then, couldnt i throw and ErrorException in my custom error handler? And then setup a custom exception handler to once again manage everything centrally(?)... Getting late will check back tomorrow when i signon
@mindfriction you could, but I think that might cause undefined behaviour, because code that comes after throwing the exception might still be executed.
Pekka
@Pekaa, so perhaps the best method is to keep my custom error handler and extending Exceptions like PDOException to handle as I want to
@mindfriction good idea, but a lot of work, as you would have to extend every throwable extension there is. Not sure whether that's practical.
Pekka