search
HomeBackend DevelopmentPHP Tutorial拦截PHP各种错误和异常,发生致命异常时进行报警,万事防患于未然

拦截PHP各种异常和错误,发生致命错误时进行报警,万事防患于未然

在日常开发中,大多数人的做法是在开发环境时开启调试模式,在产品环境关闭调试模式。在开发的时候可以查看各种错误、异常,但是在线上就把错误显示的关闭。

上面的情形看似很科学,有人解释为这样很安全,别人看不到错误,以免泄露重要信息...

但是你有没有遇到这种情况,线下好好的,一上线却运行不起来也找不到原因...

一个脚本,跑了好长一段时间,一直没有问题,有一天突然中断了,然后了也没有任何记录都不造啥原因...

线上一个付款,别人明明付了款,但是我们却没有记录到,自己亲自去实验,却是好的...

 

种种以上,都是因为大家关闭了错误信息,并且未将错误、异常记录到日志,导致那些随机发生的错误很难追踪。这样矛盾就来了,即不要显示错误,又要追踪错误,这如何实现了?

以上问题都可以通过PHP的错误、异常机制及其内建函数'set_exception_handler','set_error_handler','register_shutdown_function' 来实现

 

'set_exception_handler' 函数 用于拦截各种未捕获的异常,然后将这些交给用户自定义的方式进行处理

'set_error_handler' 函数可以拦截各种错误,然后交给用户自定义的方式进行处理

'register_shutdown_function' 函数是在PHP脚本结束时调用的函数,配合'error_get_last'可以获取最后的致命性错误

 

这个思路大体就是把错误、异常、致命性错误拦截下来,交给我们自定义的方法进行处理,我们辨别这些错误、异常是否致命,如果是则记录的数据库或者文件系统,然后使用脚本不停的扫描这些日志,发现严重错误立即发送邮件或发送短信进行报警

 

首先我们定义错误拦截类,该类用于将错误、异常拦截下来,用我们自己定义的处理方式进行处理,该类放在文件名为'errorHandler.class.php'中,代码如下

<span style="color: #008000;">/*</span><span style="color: #008000;">* * 文件名称:baseErrorHandler.class.php * 摘    要:错误拦截器父类 </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">require</span> 'errorHandlerException.class.php';<span style="color: #008000;">//</span><span style="color: #008000;">异常类</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> errorHandler{    </span><span style="color: #0000ff;">public</span> <span style="color: #800080;">$argvs</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">();    </span><span style="color: #0000ff;">public</span>     <span style="color: #800080;">$memoryReserveSize</span> = 262144;<span style="color: #008000;">//</span><span style="color: #008000;">备用内存大小</span>    <span style="color: #0000ff;">private</span> <span style="color: #800080;">$_memoryReserve</span>;<span style="color: #008000;">//</span><span style="color: #008000;">备用内存</span>    <span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:注册自定义错误、异常拦截器     * 参      数:void     * 返      回:void     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> register()    {        </span><span style="color: #008080;">ini_set</span>('display_errors', 0<span style="color: #000000;">);        </span><span style="color: #008080;">set_exception_handler</span>(<span style="color: #0000ff;">array</span>(<span style="color: #800080;">$this</span>, 'handleException'));<span style="color: #008000;">//</span><span style="color: #008000;">截获未捕获的异常</span>        <span style="color: #008080;">set_error_handler</span>(<span style="color: #0000ff;">array</span>(<span style="color: #800080;">$this</span>, 'handleError'));<span style="color: #008000;">//</span><span style="color: #008000;">截获各种错误 此处切不可掉换位置        //留下备用内存 供后面拦截致命错误使用</span>        <span style="color: #800080;">$this</span>->memoryReserveSize > 0 && <span style="color: #800080;">$this</span>->_memoryReserve = <span style="color: #008080;">str_repeat</span>('x', <span style="color: #800080;">$this</span>-><span style="color: #000000;">memoryReserveSize);        </span><span style="color: #008080;">register_shutdown_function</span>(<span style="color: #0000ff;">array</span>(<span style="color: #800080;">$this</span>, 'handleFatalError'));<span style="color: #008000;">//</span><span style="color: #008000;">截获致命性错误</span><span style="color: #000000;">    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:取消自定义错误、异常拦截器     * 参      数:void     * 返      回:void     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> unregister()    {        </span><span style="color: #008080;">restore_error_handler</span><span style="color: #000000;">();        </span><span style="color: #008080;">restore_exception_handler</span><span style="color: #000000;">();    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:处理截获的未捕获的异常     * 参      数:Exception $exception     * 返      回:void     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> handleException(<span style="color: #800080;">$exception</span><span style="color: #000000;">)    {        </span><span style="color: #800080;">$this</span>-><span style="color: #000000;">unregister();        </span><span style="color: #0000ff;">try</span><span style="color: #000000;">        {            </span><span style="color: #800080;">$this</span>->logException(<span style="color: #800080;">$exception</span><span style="color: #000000;">);            </span><span style="color: #0000ff;">exit</span>(1<span style="color: #000000;">);        }        </span><span style="color: #0000ff;">catch</span>(<span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$e</span><span style="color: #000000;">)        {            </span><span style="color: #0000ff;">exit</span>(1<span style="color: #000000;">);        }    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:处理截获的错误     * 参      数:int     $code 错误代码     * 参      数:string $message 错误信息     * 参      数:string $file 错误文件     * 参      数:int     $line 错误的行数     * 返      回:boolean     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> handleError(<span style="color: #800080;">$code</span>, <span style="color: #800080;">$message</span>, <span style="color: #800080;">$file</span>, <span style="color: #800080;">$line</span><span style="color: #000000;">)    {        </span><span style="color: #008000;">//</span><span style="color: #008000;">该处思想是将错误变成异常抛出 统一交给异常处理函数进行处理</span>        <span style="color: #0000ff;">if</span>((<span style="color: #008080;">error_reporting</span>() & <span style="color: #800080;">$code</span>) && !<span style="color: #008080;">in_array</span>(<span style="color: #800080;">$code</span>, <span style="color: #0000ff;">array</span>(<span style="color: #ff00ff;">E_NOTICE</span>, <span style="color: #ff00ff;">E_WARNING</span>, <span style="color: #ff00ff;">E_USER_NOTICE</span>, <span style="color: #ff00ff;">E_USER_WARNING</span>,<span style="color: #000000;"> E_DEPRECATED)))        {</span><span style="color: #008000;">//</span><span style="color: #008000;">此处只记录严重的错误 对于各种WARNING NOTICE不作处理</span>            <span style="color: #800080;">$exception</span> = <span style="color: #0000ff;">new</span> errorHandlerException(<span style="color: #800080;">$message</span>, <span style="color: #800080;">$code</span>, <span style="color: #800080;">$code</span>, <span style="color: #800080;">$file</span>, <span style="color: #800080;">$line</span><span style="color: #000000;">);            </span><span style="color: #800080;">$trace</span> = <span style="color: #008080;">debug_backtrace</span><span style="color: #000000;">(DEBUG_BACKTRACE_IGNORE_ARGS);            </span><span style="color: #008080;">array_shift</span>(<span style="color: #800080;">$trace</span>);<span style="color: #008000;">//</span><span style="color: #008000;">trace的第一个元素为当前对象 移除</span>            <span style="color: #0000ff;">foreach</span>(<span style="color: #800080;">$trace</span> <span style="color: #0000ff;">as</span> <span style="color: #800080;">$frame</span><span style="color: #000000;">)             {                </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$frame</span>['function'] == '__toString'<span style="color: #000000;">)                 {</span><span style="color: #008000;">//</span><span style="color: #008000;">如果错误出现在 __toString 方法中 不抛出任何异常</span>                    <span style="color: #800080;">$this</span>->handleException(<span style="color: #800080;">$exception</span><span style="color: #000000;">);                    </span><span style="color: #0000ff;">exit</span>(1<span style="color: #000000;">);                }            }            </span><span style="color: #0000ff;">throw</span> <span style="color: #800080;">$exception</span><span style="color: #000000;">;        }        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">;    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:截获致命性错误     * 参      数:void     * 返      回:void     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> handleFatalError()    {        </span><span style="color: #0000ff;">unset</span>(<span style="color: #800080;">$this</span>->_memoryReserve);<span style="color: #008000;">//</span><span style="color: #008000;">释放内存供下面处理程序使用</span>        <span style="color: #800080;">$error</span> = error_get_last();<span style="color: #008000;">//</span><span style="color: #008000;">最后一条错误信息</span>        <span style="color: #0000ff;">if</span>(errorHandlerException::isFatalError(<span style="color: #800080;">$error</span><span style="color: #000000;">))        {</span><span style="color: #008000;">//</span><span style="color: #008000;">如果是致命错误进行处理</span>            <span style="color: #800080;">$exception</span> = <span style="color: #0000ff;">new</span> errorHandlerException(<span style="color: #800080;">$error</span>['message'], <span style="color: #800080;">$error</span>['type'], <span style="color: #800080;">$error</span>['type'], <span style="color: #800080;">$error</span>['file'], <span style="color: #800080;">$error</span>['line'<span style="color: #000000;">]);            </span><span style="color: #800080;">$this</span>->logException(<span style="color: #800080;">$exception</span><span style="color: #000000;">);            </span><span style="color: #0000ff;">exit</span>(1<span style="color: #000000;">);        }    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:获取服务器IP     * 参      数:void     * 返      回:string     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getServerIp()    {        </span><span style="color: #800080;">$serverIp</span> = ''<span style="color: #000000;">;        </span><span style="color: #0000ff;">if</span>(<span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$_SERVER</span>['SERVER_ADDR'<span style="color: #000000;">]))        {            </span><span style="color: #800080;">$serverIp</span> = <span style="color: #800080;">$_SERVER</span>['SERVER_ADDR'<span style="color: #000000;">];        }        </span><span style="color: #0000ff;">elseif</span>(<span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$_SERVER</span>['LOCAL_ADDR'<span style="color: #000000;">]))        {            </span><span style="color: #800080;">$serverIp</span> = <span style="color: #800080;">$_SERVER</span>['LOCAL_ADDR'<span style="color: #000000;">];        }        </span><span style="color: #0000ff;">elseif</span>(<span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$_SERVER</span>['HOSTNAME'<span style="color: #000000;">]))        {            </span><span style="color: #800080;">$serverIp</span> = <span style="color: #008080;">gethostbyname</span>(<span style="color: #800080;">$_SERVER</span>['HOSTNAME'<span style="color: #000000;">]);        }        </span><span style="color: #0000ff;">else</span><span style="color: #000000;">        {            </span><span style="color: #800080;">$serverIp</span> = <span style="color: #008080;">getenv</span>('SERVER_ADDR'<span style="color: #000000;">);        }                        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$serverIp</span><span style="color: #000000;">;     }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:获取当前URI信息     * 参      数:void     * 返      回:string $url     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getCurrentUri()    {        </span><span style="color: #800080;">$uri</span> = ''<span style="color: #000000;">;        </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$_SERVER</span> ["REMOTE_ADDR"<span style="color: #000000;">])        {</span><span style="color: #008000;">//</span><span style="color: #008000;">浏览器浏览模式</span>            <span style="color: #800080;">$uri</span> = 'http://' . <span style="color: #800080;">$_SERVER</span>['SERVER_NAME'] . <span style="color: #800080;">$_SERVER</span>['REQUEST_URI'<span style="color: #000000;">];        }        </span><span style="color: #0000ff;">else</span><span style="color: #000000;">        {</span><span style="color: #008000;">//</span><span style="color: #008000;">命令行模式</span>            <span style="color: #800080;">$params</span> = <span style="color: #800080;">$this</span>-><span style="color: #000000;">argvs;            </span><span style="color: #800080;">$uri</span> = <span style="color: #800080;">$params</span>[0<span style="color: #000000;">];            </span><span style="color: #008080;">array_shift</span>(<span style="color: #800080;">$params</span><span style="color: #000000;">);            </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span> = 0, <span style="color: #800080;">$len</span> = <span style="color: #008080;">count</span>(<span style="color: #800080;">$params</span>); <span style="color: #800080;">$i</span> $len; <span style="color: #800080;">$i</span>++<span style="color: #000000;">)            {                </span><span style="color: #800080;">$uri</span> .= ' ' . <span style="color: #800080;">$params</span>[<span style="color: #800080;">$i</span><span style="color: #000000;">];            }        }        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$uri</span><span style="color: #000000;">;    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:记录异常信息     * 参      数:errorHandlerException $e 错误异常     * 返      回:boolean 是否保存成功     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> logException(<span style="color: #800080;">$e</span><span style="color: #000000;">)    {        </span><span style="color: #800080;">$error</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(                        </span>'add_time'     =>     <span style="color: #008080;">time</span>(),                        'title'     =>     errorHandlerException::getName(<span style="color: #800080;">$e</span>->getCode()),<span style="color: #008000;">//</span><span style="color: #008000;">这里获取用户友好型名称</span>                        'message'     =>     <span style="color: #0000ff;">array</span>(),                        'server_ip' =>     <span style="color: #800080;">$this</span>->getServerIp(),                        'code'         =>     errorHandlerException::getLocalCode(<span style="color: #800080;">$e</span>->getCode()),<span style="color: #008000;">//</span><span style="color: #008000;">这里为各种错误定义一个编号以便查找</span>                        'file'         =>  <span style="color: #800080;">$e</span>->getFile(),                        'line'         =>     <span style="color: #800080;">$e</span>->getLine(),                        'url'        =>  <span style="color: #800080;">$this</span>->getCurrentUri(),<span style="color: #000000;">                    );        </span><span style="color: #0000ff;">do</span><span style="color: #000000;">        {            </span><span style="color: #008000;">//</span><span style="color: #008000;">$e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage() . '(' . $e->getCode() . ')'</span>            <span style="color: #800080;">$message</span> = (<span style="color: #0000ff;">string</span>)<span style="color: #800080;">$e</span><span style="color: #000000;">;            </span><span style="color: #800080;">$error</span>['message'][] = <span style="color: #800080;">$message</span><span style="color: #000000;">;        } </span><span style="color: #0000ff;">while</span>(<span style="color: #800080;">$e</span> = <span style="color: #800080;">$e</span>-><span style="color: #000000;">getPrevious());        </span><span style="color: #800080;">$error</span>['message'] = <span style="color: #008080;">implode</span>("\r\n", <span style="color: #800080;">$error</span>['message'<span style="color: #000000;">]);        </span><span style="color: #800080;">$this</span>->logError(<span style="color: #800080;">$error</span><span style="color: #000000;">);    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:记录异常信息     * 参      数:array $error = array(     *                                    'time' => int,      *                                    'title' => 'string',      *                                    'message' => 'string',      *                                    'code' => int,     *                                    'server_ip' => 'string'     *                                     'file'     =>  'string',     *                                    'line' => int,     *                                    'url' => 'string',     *                                );     * 返      回:boolean 是否保存成功     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> logError(<span style="color: #800080;">$error</span><span style="color: #000000;">)    {        </span><span style="color: #008000;">/*</span><span style="color: #008000;">这里去实现如何将错误信息记录到日志</span><span style="color: #008000;">*/</span><span style="color: #000000;">    }}</span>

上述代码中,有个'errorHandlerException'类,该类放在文件'errorHandlerException.class.php'中,该类用于将错误转换为异常,以便记录错误发生的文件、行号、错误代码、错误信息等信息,同时其方法'isFatalError'用于辨别该错误是否是致命性错误。这里我们为了方便管理,将错误进行编号并命名。该类的代码如下

<span style="color: #008000;">/*</span><span style="color: #008000;">* * 文件名称:errorHandlerException.class.php * 摘    要:自定义错误异常类 该类继承至PHP内置的错误异常类 </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">class</span> errorHandlerException <span style="color: #0000ff;">extends</span><span style="color: #000000;"> ErrorException{    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #800080;">$localCode</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(                                        </span><span style="color: #ff00ff;">E_COMPILE_ERROR</span> => 4001,                                        <span style="color: #ff00ff;">E_COMPILE_WARNING</span> => 4002,                                        <span style="color: #ff00ff;">E_CORE_ERROR</span> => 4003,                                        <span style="color: #ff00ff;">E_CORE_WARNING</span> => 4004,<span style="color: #000000;">                                        E_DEPRECATED </span>=> 4005,                                        <span style="color: #ff00ff;">E_ERROR</span> => 4006,                                        <span style="color: #ff00ff;">E_NOTICE</span> => 4007,                                        <span style="color: #ff00ff;">E_PARSE</span> => 4008,<span style="color: #000000;">                                        E_RECOVERABLE_ERROR </span>=> 4009,                                        <span style="color: #ff00ff;">E_STRICT</span> => 4010,<span style="color: #000000;">                                        E_USER_DEPRECATED </span>=> 4011,                                        <span style="color: #ff00ff;">E_USER_ERROR</span> => 4012,                                        <span style="color: #ff00ff;">E_USER_NOTICE</span> => 4013,                                        <span style="color: #ff00ff;">E_USER_WARNING</span> => 4014,                                        <span style="color: #ff00ff;">E_WARNING</span> => 4015,                                        4016 => 4016,<span style="color: #000000;">                                    );    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #800080;">$localName</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(                                        </span><span style="color: #ff00ff;">E_COMPILE_ERROR</span> => 'PHP Compile Error',                                        <span style="color: #ff00ff;">E_COMPILE_WARNING</span> => 'PHP Compile Warning',                                        <span style="color: #ff00ff;">E_CORE_ERROR</span> => 'PHP Core Error',                                        <span style="color: #ff00ff;">E_CORE_WARNING</span> => 'PHP Core Warning',<span style="color: #000000;">                                        E_DEPRECATED </span>=> 'PHP Deprecated Warning',                                        <span style="color: #ff00ff;">E_ERROR</span> => 'PHP Fatal Error',                                        <span style="color: #ff00ff;">E_NOTICE</span> => 'PHP Notice',                                        <span style="color: #ff00ff;">E_PARSE</span> => 'PHP Parse Error',<span style="color: #000000;">                                        E_RECOVERABLE_ERROR </span>=> 'PHP Recoverable Error',                                        <span style="color: #ff00ff;">E_STRICT</span> => 'PHP Strict Warning',<span style="color: #000000;">                                        E_USER_DEPRECATED </span>=> 'PHP User Deprecated Warning',                                        <span style="color: #ff00ff;">E_USER_ERROR</span> => 'PHP User Error',                                        <span style="color: #ff00ff;">E_USER_NOTICE</span> => 'PHP User Notice',                                        <span style="color: #ff00ff;">E_USER_WARNING</span> => 'PHP User Warning',                                        <span style="color: #ff00ff;">E_WARNING</span> => 'PHP Warning',                                        4016 => 'Customer`s Error',<span style="color: #000000;">                                    );    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:构造函数     * 摘      要:相关知识请查看 http://php.net/manual/en/errorexception.construct.php     *        * 参      数:string        $message     异常信息(可选)     *              int         $code         异常代码(可选)     *              int         $severity     *              string     $filename     异常文件(可选)     *              int         $line         异常的行数(可选)     *           Exception  $previous   上一个异常(可选)     *     * 返      回:void     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$message</span> = '', <span style="color: #800080;">$code</span> = 0, <span style="color: #800080;">$severity</span> = 1, <span style="color: #800080;">$filename</span> = <span style="color: #ff00ff;">__FILE__</span>, <span style="color: #800080;">$line</span> = <span style="color: #ff00ff;">__LINE__</span>, <span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$previous</span> = <span style="color: #0000ff;">null</span><span style="color: #000000;">)    {        parent</span>::__construct(<span style="color: #800080;">$message</span>, <span style="color: #800080;">$code</span>, <span style="color: #800080;">$severity</span>, <span style="color: #800080;">$filename</span>, <span style="color: #800080;">$line</span>, <span style="color: #800080;">$previous</span><span style="color: #000000;">);    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:是否是致命性错误     * 参      数:array $error     * 返      回:boolean     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span> isFatalError(<span style="color: #800080;">$error</span><span style="color: #000000;">)    {        </span><span style="color: #800080;">$fatalErrors</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">(                                </span><span style="color: #ff00ff;">E_ERROR</span>,                                 <span style="color: #ff00ff;">E_PARSE</span>,                                 <span style="color: #ff00ff;">E_CORE_ERROR</span>,                                <span style="color: #ff00ff;">E_CORE_WARNING</span>,                                 <span style="color: #ff00ff;">E_COMPILE_ERROR</span>,                                 <span style="color: #ff00ff;">E_COMPILE_WARNING</span><span style="color: #000000;">                            );        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">isset</span>(<span style="color: #800080;">$error</span>['type']) && <span style="color: #008080;">in_array</span>(<span style="color: #800080;">$error</span>['type'], <span style="color: #800080;">$fatalErrors</span><span style="color: #000000;">);    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:根据原始的错误代码得到本地的错误代码     * 参      数:int $code     * 返      回:int $localCode     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span> getLocalCode(<span style="color: #800080;">$code</span><span style="color: #000000;">)    {        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">isset</span>(self::<span style="color: #800080;">$localCode</span>[<span style="color: #800080;">$code</span>]) ? self::<span style="color: #800080;">$localCode</span>[<span style="color: #800080;">$code</span>] : self::<span style="color: #800080;">$localCode</span>[4016<span style="color: #000000;">];    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:根据原始的错误代码获取用户友好型名称     * 参      数:int      * 返      回:string $name     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span> getName(<span style="color: #800080;">$code</span><span style="color: #000000;">)    {        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">isset</span>(self::<span style="color: #800080;">$localName</span>[<span style="color: #800080;">$code</span>]) ? self::<span style="color: #800080;">$localName</span>[<span style="color: #800080;">$code</span>] : self::<span style="color: #800080;">$localName</span>[4016<span style="color: #000000;">];    }</span>

在错误拦截类中,需要用户自己定义实现错误记录的方法('logException'),这个地方需要注意,有些错误可能在一段时间内不断发生,因此只需记录一次即可,你可以使用错误代码、文件、行号、错误详情 生成一个MD5值用于记录该错误是否已经被记录,如果在规定时间内(一个小时)已经被记录过则不需要再进行记录

 

然后我们定义一个文件,用于实例化以上类,捕获各种错误、异常,该文件命名为'registerErrorHandler.php', 内如如下

<span style="color: #008000;">/*</span><span style="color: #008000;">* 使用方法介绍:* 在入口处引入该文件即可,然后可以在该文件中定义调试模式常量'DEBUG_ERROR'** <?php *   *    require 'registerErrorHandler.php';*   * ?></span><span style="color: #008000;">*/</span><span style="color: #008000;">/*</span><span style="color: #008000;">** 调试错误模式:* 0                =>            非调试模式,不显示异常、错误信息但记录异常、错误信息* 1                =>            调试模式,显示异常、错误信息但不记录异常、错误信息</span><span style="color: #008000;">*/</span><span style="color: #008080;">define</span>('DEBUG_ERROR', 0<span style="color: #000000;">);</span><span style="color: #0000ff;">require</span> 'errorHandler.class.php'<span style="color: #000000;">;</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> registerErrorHandler{    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * 方      法:注册异常、错误拦截     * 参      数:void     * 返      回:void     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> register()    {        </span><span style="color: #0000ff;">global</span> <span style="color: #800080;">$argv</span><span style="color: #000000;">;        </span><span style="color: #0000ff;">if</span><span style="color: #000000;">(DEBUG_ERROR)        {</span><span style="color: #008000;">//</span><span style="color: #008000;">如果开启调试模式</span>            <span style="color: #008080;">ini_set</span>('display_errors', 1<span style="color: #000000;">);            </span><span style="color: #0000ff;">return</span><span style="color: #000000;">;        }        </span><span style="color: #008000;">//</span><span style="color: #008000;">如果不开启调试模式</span>        <span style="color: #008080;">ini_set</span>('error_reporting', -1<span style="color: #000000;">);        </span><span style="color: #008080;">ini_set</span>('display_errors', 0<span style="color: #000000;">);        </span><span style="color: #800080;">$handler</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> errorHandler();        </span><span style="color: #800080;">$handler</span>->argvs = <span style="color: #800080;">$argv</span>;<span style="color: #008000;">//</span><span style="color: #008000;">此处主要兼容命令行模式下获取参数</span>        <span style="color: #800080;">$handler</span>-><span style="color: #000000;">register();    }    }registerErrorHandler</span>::register();

剩下的就是需要你在你的入口文件引入该文件,定义调试模式,然后实现你自己记录错误的方法即可

需要注意的是,有些错误在你进行注册之前已经发生并且导致脚本中断是无法记录下来的,因为此时'registerErrorHandler::register()' 尚未执行已经中断了

还有就是'set_error_handler'这个函数不能捕获下面类型的错误 E_ERROR、 E_PARSE、 E_CORE_ERROR、 E_CORE_WARNINGE_COMPILE_ERROR、 E_COMPILE_WARNING, 这个可以在官方文档中看到,但是本处无妨,因为以上错误是解析、编译错误,这些都没有通过,你是不可能发布上线的

 

以上代码经过严格测试,并且已经应用在线上环境,大家可以根据自己需要进行更改使用

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.