Share an exception handler for php

  • 2021-07-02 23:44:20
  • OfStack

Direct code


<?php
//exceptionHandle.php xiecongwen 20140620
//define('DEBUG',true);
/**
* Display all errors when APPLICATION_ENV is development.
*/
if (defined('DEBUG')) {
error_reporting(E_ALL);
ini_set("display_errors", 1);
}
if(!defined('DEBUG')){
/**
*  When a major error occurs,   Write a journal   And friendly prompt users 
* (PS: Just write the code here , Because when registering elsewhere, , There is a problem and the configuration function cannot be called . To be perfected ...)
*/
function shutdownHandler()
{
/**
*  Write a journal   Write directly under the root directory here shutdownlog.txt
*/
$lasterror = error_get_last();
if($lasterror){
$error = strval(date("Y-m-d h:i:s")).'=>'."[SHUTDOWN] lvl:" . $lasterror['type'] . " | msg:" . $lasterror['message'] . " | file:" . $lasterror['file'] . " | ln:" . $lasterror['line']."\n";
file_put_contents('./log/'.date("Ymd").'shutdownlog.txt',$error,FILE_APPEND);
// Friendly prompt user 
ob_end_clean();
die(' I'm sorry , I made a mistake! ');
}
}
register_shutdown_function('shutdownHandler');
}
if(!defined('DEBUG')){
 
function errorHandler($errno, $errstr = '', $errfile = '', $errline = 0)
{
// Write a journal 
$exception = new \ErrorException($errstr, 0, $errno, $errfile, $errline);
$msg = strval(date("Y-m-d h:i:s")).'=>'.'Type:'.getErrTypeName($errno).' '.getMsg($exception);
file_put_contents('./log/'.date("Ymd").'error.txt',$msg,FILE_APPEND);
switch ($errno)
{
case E_NOTICE:return ;
case E_DEPRECATED:return;
}
throw $exception;
}
function getErrTypeName($errno)
{
switch ($errno)
{
case E_NOTICE:return 'E_NOTICE' ;
case E_DEPRECATED:return 'E_DEPRECATED';
default:return $errno;
}
}
function exceptionHandler($ex)
{
$msg = strval(date("Y-m-d h:i:s")).'=>'.getMsg($ex);
file_put_contents('./log/'.date("Ymd").'exception.txt',$msg,FILE_APPEND);
}
function getMsg($exception)
{
// Get the most accurate exception  
while($exception->getPrevious())$exception = $exception->getPrevious();
$msg = ' Message: '.$exception->getMessage();
$msg .= ' File: '.$exception->getFile().':'.$exception->getLine()."\n";
return $msg;
}
set_error_handler('errorHandler',E_ALL);
set_exception_handler('exceptionHandler');
}
?>


Related articles: