How to handle php errors and exceptions centrally

2019-08-30 22:22发布

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;

}

1条回答
疯言疯语
2楼-- · 2019-08-30 23:02

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.

查看更多
登录 后发表回答