Rumah >pembangunan bahagian belakang >tutorial php >拦截PHP各种异常和错误,发生致命错误时进行报警,万事防患于未然,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>/*</span><span>* * 文件名称:baseErrorHandler.class.php * 摘 要:错误拦截器父类 </span><span>*/</span> <span>require</span> 'errorHandlerException.class.php';<span>//</span><span>异常类</span> <span>class</span><span> errorHandler { </span><span>public</span> <span>$argvs</span> = <span>array</span><span>(); </span><span>public</span> <span>$memoryReserveSize</span> = 262144;<span>//</span><span>备用内存大小</span> <span>private</span> <span>$_memoryReserve</span>;<span>//</span><span>备用内存</span> <span>/*</span><span>* * 方 法:注册自定义错误、异常拦截器 * 参 数:void * 返 回:void </span><span>*/</span> <span>public</span> <span>function</span><span> register() { </span><span>ini_set</span>('display_errors', 0<span>); </span><span>set_exception_handler</span>(<span>array</span>(<span>$this</span>, 'handleException'));<span>//</span><span>截获未捕获的异常</span> <span>set_error_handler</span>(<span>array</span>(<span>$this</span>, 'handleError'));<span>//</span><span>截获各种错误 此处切不可掉换位置 //留下备用内存 供后面拦截致命错误使用</span> <span>$this</span>->memoryReserveSize > 0 && <span>$this</span>->_memoryReserve = <span>str_repeat</span>('x', <span>$this</span>-><span>memoryReserveSize); </span><span>register_shutdown_function</span>(<span>array</span>(<span>$this</span>, 'handleFatalError'));<span>//</span><span>截获致命性错误</span> <span> } </span><span>/*</span><span>* * 方 法:取消自定义错误、异常拦截器 * 参 数:void * 返 回:void </span><span>*/</span> <span>public</span> <span>function</span><span> unregister() { </span><span>restore_error_handler</span><span>(); </span><span>restore_exception_handler</span><span>(); } </span><span>/*</span><span>* * 方 法:处理截获的未捕获的异常 * 参 数:Exception $exception * 返 回:void </span><span>*/</span> <span>public</span> <span>function</span> handleException(<span>$exception</span><span>) { </span><span>$this</span>-><span>unregister(); </span><span>try</span><span> { </span><span>$this</span>->logException(<span>$exception</span><span>); </span><span>exit</span>(1<span>); } </span><span>catch</span>(<span>Exception</span> <span>$e</span><span>) { </span><span>exit</span>(1<span>); } } </span><span>/*</span><span>* * 方 法:处理截获的错误 * 参 数:int $code 错误代码 * 参 数:string $message 错误信息 * 参 数:string $file 错误文件 * 参 数:int $line 错误的行数 * 返 回:boolean </span><span>*/</span> <span>public</span> <span>function</span> handleError(<span>$code</span>, <span>$message</span>, <span>$file</span>, <span>$line</span><span>) { </span><span>//</span><span>该处思想是将错误变成异常抛出 统一交给异常处理函数进行处理</span> <span>if</span>((<span>error_reporting</span>() & <span>$code</span>) && !<span>in_array</span>(<span>$code</span>, <span>array</span>(<span>E_NOTICE</span>, <span>E_WARNING</span>, <span>E_USER_NOTICE</span>, <span>E_USER_WARNING</span>,<span> E_DEPRECATED))) {</span><span>//</span><span>此处只记录严重的错误 对于各种WARNING NOTICE不作处理</span> <span>$exception</span> = <span>new</span> errorHandlerException(<span>$message</span>, <span>$code</span>, <span>$code</span>, <span>$file</span>, <span>$line</span><span>); </span><span>$trace</span> = <span>debug_backtrace</span><span>(DEBUG_BACKTRACE_IGNORE_ARGS); </span><span>array_shift</span>(<span>$trace</span>);<span>//</span><span>trace的第一个元素为当前对象 移除</span> <span>foreach</span>(<span>$trace</span> <span>as</span> <span>$frame</span><span>) { </span><span>if</span>(<span>$frame</span>['function'] == '__toString'<span>) {</span><span>//</span><span>如果错误出现在 __toString 方法中 不抛出任何异常</span> <span>$this</span>->handleException(<span>$exception</span><span>); </span><span>exit</span>(1<span>); } } </span><span>throw</span> <span>$exception</span><span>; } </span><span>return</span> <span>false</span><span>; } </span><span>/*</span><span>* * 方 法:截获致命性错误 * 参 数:void * 返 回:void </span><span>*/</span> <span>public</span> <span>function</span><span> handleFatalError() { </span><span>unset</span>(<span>$this</span>->_memoryReserve);<span>//</span><span>释放内存供下面处理程序使用</span> <span>$error</span> = error_get_last();<span>//</span><span>最后一条错误信息</span> <span>if</span>(errorHandlerException::isFatalError(<span>$error</span><span>)) {</span><span>//</span><span>如果是致命错误进行处理</span> <span>$exception</span> = <span>new</span> errorHandlerException(<span>$error</span>['message'], <span>$error</span>['type'], <span>$error</span>['type'], <span>$error</span>['file'], <span>$error</span>['line'<span>]); </span><span>$this</span>->logException(<span>$exception</span><span>); </span><span>exit</span>(1<span>); } } </span><span>/*</span><span>* * 方 法:获取服务器IP * 参 数:void * 返 回:string </span><span>*/</span> <span>final</span> <span>public</span> <span>function</span><span> getServerIp() { </span><span>$serverIp</span> = ''<span>; </span><span>if</span>(<span>isset</span>(<span>$_SERVER</span>['SERVER_ADDR'<span>])) { </span><span>$serverIp</span> = <span>$_SERVER</span>['SERVER_ADDR'<span>]; } </span><span>elseif</span>(<span>isset</span>(<span>$_SERVER</span>['LOCAL_ADDR'<span>])) { </span><span>$serverIp</span> = <span>$_SERVER</span>['LOCAL_ADDR'<span>]; } </span><span>elseif</span>(<span>isset</span>(<span>$_SERVER</span>['HOSTNAME'<span>])) { </span><span>$serverIp</span> = <span>gethostbyname</span>(<span>$_SERVER</span>['HOSTNAME'<span>]); } </span><span>else</span><span> { </span><span>$serverIp</span> = <span>getenv</span>('SERVER_ADDR'<span>); } </span><span>return</span> <span>$serverIp</span><span>; } </span><span>/*</span><span>* * 方 法:获取当前URI信息 * 参 数:void * 返 回:string $url </span><span>*/</span> <span>public</span> <span>function</span><span> getCurrentUri() { </span><span>$uri</span> = ''<span>; </span><span>if</span>(<span>$_SERVER</span> ["REMOTE_ADDR"<span>]) {</span><span>//</span><span>浏览器浏览模式</span> <span>$uri</span> = 'http://' . <span>$_SERVER</span>['SERVER_NAME'] . <span>$_SERVER</span>['REQUEST_URI'<span>]; } </span><span>else</span><span> {</span><span>//</span><span>命令行模式</span> <span>$params</span> = <span>$this</span>-><span>argvs; </span><span>$uri</span> = <span>$params</span>[0<span>]; </span><span>array_shift</span>(<span>$params</span><span>); </span><span>for</span>(<span>$i</span> = 0, <span>$len</span> = <span>count</span>(<span>$params</span>); <span>$i</span> < <span>$len</span>; <span>$i</span>++<span>) { </span><span>$uri</span> .= ' ' . <span>$params</span>[<span>$i</span><span>]; } } </span><span>return</span> <span>$uri</span><span>; } </span><span>/*</span><span>* * 方 法:记录异常信息 * 参 数:errorHandlerException $e 错误异常 * 返 回:boolean 是否保存成功 </span><span>*/</span> <span>final</span> <span>public</span> <span>function</span> logException(<span>$e</span><span>) { </span><span>$error</span> = <span>array</span><span>( </span>'add_time' => <span>time</span>(), 'title' => errorHandlerException::getName(<span>$e</span>->getCode()),<span>//</span><span>这里获取用户友好型名称</span> 'message' => <span>array</span>(), 'server_ip' => <span>$this</span>->getServerIp(), 'code' => errorHandlerException::getLocalCode(<span>$e</span>->getCode()),<span>//</span><span>这里为各种错误定义一个编号以便查找</span> 'file' => <span>$e</span>->getFile(), 'line' => <span>$e</span>->getLine(), 'url' => <span>$this</span>->getCurrentUri(),<span> ); </span><span>do</span><span> { </span><span>//</span><span>$e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage() . '(' . $e->getCode() . ')'</span> <span>$message</span> = (<span>string</span>)<span>$e</span><span>; </span><span>$error</span>['message'][] = <span>$message</span><span>; } </span><span>while</span>(<span>$e</span> = <span>$e</span>-><span>getPrevious()); </span><span>$error</span>['message'] = <span>implode</span>("\r\n", <span>$error</span>['message'<span>]); </span><span>$this</span>->logError(<span>$error</span><span>); } </span><span>/*</span><span>* * 方 法:记录异常信息 * 参 数:array $error = array( * 'time' => int, * 'title' => 'string', * 'message' => 'string', * 'code' => int, * 'server_ip' => 'string' * 'file' => 'string', * 'line' => int, * 'url' => 'string', * ); * 返 回:boolean 是否保存成功 </span><span>*/</span> <span>public</span> <span>function</span> logError(<span>$error</span><span>) { </span><span>/*</span><span>这里去实现如何将错误信息记录到日志</span><span>*/</span><span> } }</span>
上述代码中,有个'errorHandlerException'类,该类放在文件'errorHandlerException.class.php'中,该类用于将错误转换为异常,以便记录错误发生的文件、行号、错误代码、错误信息等信息,同时其方法'isFatalError'用于辨别该错误是否是致命性错误。这里我们为了方便管理,将错误进行编号并命名。该类的代码如下
<span>/*</span><span>* * 文件名称:errorHandlerException.class.php * 摘 要:自定义错误异常类 该类继承至PHP内置的错误异常类 </span><span>*/</span> <span>class</span> errorHandlerException <span>extends</span><span> ErrorException { </span><span>public</span> <span>static</span> <span>$localCode</span> = <span>array</span><span>( </span><span>E_COMPILE_ERROR</span> => 4001, <span>E_COMPILE_WARNING</span> => 4002, <span>E_CORE_ERROR</span> => 4003, <span>E_CORE_WARNING</span> => 4004,<span> E_DEPRECATED </span>=> 4005, <span>E_ERROR</span> => 4006, <span>E_NOTICE</span> => 4007, <span>E_PARSE</span> => 4008,<span> E_RECOVERABLE_ERROR </span>=> 4009, <span>E_STRICT</span> => 4010,<span> E_USER_DEPRECATED </span>=> 4011, <span>E_USER_ERROR</span> => 4012, <span>E_USER_NOTICE</span> => 4013, <span>E_USER_WARNING</span> => 4014, <span>E_WARNING</span> => 4015, 4016 => 4016,<span> ); </span><span>public</span> <span>static</span> <span>$localName</span> = <span>array</span><span>( </span><span>E_COMPILE_ERROR</span> => 'PHP Compile Error', <span>E_COMPILE_WARNING</span> => 'PHP Compile Warning', <span>E_CORE_ERROR</span> => 'PHP Core Error', <span>E_CORE_WARNING</span> => 'PHP Core Warning',<span> E_DEPRECATED </span>=> 'PHP Deprecated Warning', <span>E_ERROR</span> => 'PHP Fatal Error', <span>E_NOTICE</span> => 'PHP Notice', <span>E_PARSE</span> => 'PHP Parse Error',<span> E_RECOVERABLE_ERROR </span>=> 'PHP Recoverable Error', <span>E_STRICT</span> => 'PHP Strict Warning',<span> E_USER_DEPRECATED </span>=> 'PHP User Deprecated Warning', <span>E_USER_ERROR</span> => 'PHP User Error', <span>E_USER_NOTICE</span> => 'PHP User Notice', <span>E_USER_WARNING</span> => 'PHP User Warning', <span>E_WARNING</span> => 'PHP Warning', 4016 => 'Customer`s Error',<span> ); </span><span>/*</span><span>* * 方 法:构造函数 * 摘 要:相关知识请查看 http://php.net/manual/en/errorexception.construct.php * * 参 数:string $message 异常信息(可选) * int $code 异常代码(可选) * int $severity * string $filename 异常文件(可选) * int $line 异常的行数(可选) * Exception $previous 上一个异常(可选) * * 返 回:void </span><span>*/</span> <span>public</span> <span>function</span> __construct(<span>$message</span> = '', <span>$code</span> = 0, <span>$severity</span> = 1, <span>$filename</span> = <span>__FILE__</span>, <span>$line</span> = <span>__LINE__</span>, <span>Exception</span> <span>$previous</span> = <span>null</span><span>) { parent</span>::__construct(<span>$message</span>, <span>$code</span>, <span>$severity</span>, <span>$filename</span>, <span>$line</span>, <span>$previous</span><span>); } </span><span>/*</span><span>* * 方 法:是否是致命性错误 * 参 数:array $error * 返 回:boolean </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> isFatalError(<span>$error</span><span>) { </span><span>$fatalErrors</span> = <span>array</span><span>( </span><span>E_ERROR</span>, <span>E_PARSE</span>, <span>E_CORE_ERROR</span>, <span>E_CORE_WARNING</span>, <span>E_COMPILE_ERROR</span>, <span>E_COMPILE_WARNING</span><span> ); </span><span>return</span> <span>isset</span>(<span>$error</span>['type']) && <span>in_array</span>(<span>$error</span>['type'], <span>$fatalErrors</span><span>); } </span><span>/*</span><span>* * 方 法:根据原始的错误代码得到本地的错误代码 * 参 数:int $code * 返 回:int $localCode </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> getLocalCode(<span>$code</span><span>) { </span><span>return</span> <span>isset</span>(self::<span>$localCode</span>[<span>$code</span>]) ? self::<span>$localCode</span>[<span>$code</span>] : self::<span>$localCode</span>[4016<span>]; } </span><span>/*</span><span>* * 方 法:根据原始的错误代码获取用户友好型名称 * 参 数:int * 返 回:string $name </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span> getName(<span>$code</span><span>) { </span><span>return</span> <span>isset</span>(self::<span>$localName</span>[<span>$code</span>]) ? self::<span>$localName</span>[<span>$code</span>] : self::<span>$localName</span>[4016<span>]; }</span>
在错误拦截类中,需要用户自己定义实现错误记录的方法('logException'),这个地方需要注意,有些错误可能在一段时间内不断发生,因此只需记录一次即可,你可以使用错误代码、文件、行号、错误详情 生成一个MD5值用于记录该错误是否已经被记录,如果在规定时间内(一个小时)已经被记录过则不需要再进行记录
然后我们定义一个文件,用于实例化以上类,捕获各种错误、异常,该文件命名为'registerErrorHandler.php', 内如如下
<span>/*</span><span> * 使用方法介绍: * 在入口处引入该文件即可,然后可以在该文件中定义调试模式常量'DEBUG_ERROR' * * <?php * * require 'registerErrorHandler.php'; * * ?> </span><span>*/</span> <span>/*</span><span>* * 调试错误模式: * 0 => 非调试模式,不显示异常、错误信息但记录异常、错误信息 * 1 => 调试模式,显示异常、错误信息但不记录异常、错误信息 </span><span>*/</span> <span>define</span>('DEBUG_ERROR', 0<span>); </span><span>require</span> 'errorHandler.class.php'<span>; </span><span>class</span><span> registerErrorHandler { </span><span>/*</span><span>* * 方 法:注册异常、错误拦截 * 参 数:void * 返 回:void </span><span>*/</span> <span>public</span> <span>static</span> <span>function</span><span> register() { </span><span>global</span> <span>$argv</span><span>; </span><span>if</span><span>(DEBUG_ERROR) {</span><span>//</span><span>如果开启调试模式</span> <span>ini_set</span>('display_errors', 1<span>); </span><span>return</span><span>; } </span><span>//</span><span>如果不开启调试模式</span> <span>ini_set</span>('error_reporting', -1<span>); </span><span>ini_set</span>('display_errors', 0<span>); </span><span>$handler</span> = <span>new</span><span> errorHandler(); </span><span>$handler</span>->argvs = <span>$argv</span>;<span>//</span><span>此处主要兼容命令行模式下获取参数</span> <span>$handler</span>-><span>register(); } } registerErrorHandler</span>::register();
剩下的就是需要你在你的入口文件引入该文件,定义调试模式,然后实现你自己记录错误的方法即可
需要注意的是,有些错误在你进行注册之前已经发生并且导致脚本中断是无法记录下来的,因为此时'registerErrorHandler::register()' 尚未执行已经中断了
还有就是'set_error_handler'这个函数不能捕获下面类型的错误 E_ERROR
、 E_PARSE
、 E_CORE_ERROR
、 E_CORE_WARNING
、E_COMPILE_ERROR
、 E_COMPILE_WARNING, 这个可以在官方文档中看到,但是本处无妨,因为以上错误是解析、编译错误,这些都没有通过,你是不可能发布上线的
以上代码经过严格测试,并且已经应用在线上环境,大家可以根据自己需要进行更改使用