How to handle php errors and exceptions centrally

旧时模样 提交于 2019-12-11 18:16:08

问题


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:


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.



来源:https://stackoverflow.com/questions/3502286/how-to-handle-php-errors-and-exceptions-centrally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!