set_error_handler

最后更新于:2022-04-02 02:28:36

[TOC] ## 概述 设置用户自定义的错误处理函数 格式 ``` set_error_handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] ) : bool ``` ## 示例 ### 自定义错误 ``` // 取消系统定义的错误显示 // 我们将要定义自己的错误处理 error_reporting(0); // 使用自定义错误处理 set_error_handler("userErrorHandler"); // 用户自定义错误处理函数 function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) { // 错误发生的时间 $dt = date("Y-m-d H:i:s (T)"); // 定义错误字符串的关联数组 // 在这里我们只考虑 // E_WARNING, E_NOTICE, E_USER_ERROR, // E_USER_WARNING 和 E_USER_NOTICE $errortype = array ( E_ERROR => 'Error', E_WARNING => 'Warning', E_PARSE => 'Parsing Error', E_NOTICE => 'Notice', E_CORE_ERROR => 'Core Error', E_CORE_WARNING => 'Core Warning', E_COMPILE_ERROR => 'Compile Error', E_COMPILE_WARNING => 'Compile Warning', E_USER_ERROR => 'User Error', E_USER_WARNING => 'User Warning', E_USER_NOTICE => 'User Notice', E_STRICT => 'Runtime Notice', E_RECOVERABLE_ERROR => 'Catchable Fatal Error' ); // 设置要保存变量跟踪信息的错误类别 $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE); $err = "\n"; $err .= "\t" . $dt . "\n"; $err .= "\t" . $errno . "\n"; $err .= "\t" . $errortype[$errno] . "\n"; $err .= "\t" . $errmsg . "\n"; $err .= "\t" . $filename . "\n"; $err .= "\t" . $linenum . "\n"; if (in_array($errno, $user_errors)) { $err .= "\t" . wddx_serialize_value($vars, "Variables") . "\n"; } $err .= "\n\n"; // for testing // echo $err; // 记录错误信息到错误日志,并在发生关键用户错误时发送电子邮件 // 直接输出 echo $err; // 或者保存文件 error_log($err, 3, "php_err.log"); } function throwError($msg,$errorType = E_USER_NOTICE){ trigger_error($msg,$errorType); } // 未定义的常量,将产生一个警告 $t = I_AM_NOT_DEFINED; // 输出警告 $a = 1/0; throwError("产生一个错误",E_ERROR); throwError("产生一个警告",E_WARNING); throwError("产生一个注意",E_NOTICE); ``` output ``` 2020-08-28 15:09:40 (CEST) 2 Warning Use of undefined constant I_AM_NOT_DEFINED - assumed 'I_AM_NOT_DEFINED' (this will throw an Error in a future version of PHP) /Users/idcpj/Web/phalcon/demo/phpinfo.php 73 2020-08-28 15:09:40 (CEST) 2 Warning Division by zero /Users/idcpj/Web/phalcon/demo/phpinfo.php 76 2020-08-28 15:09:40 (CEST) 2 Warning Invalid error type specified /Users/idcpj/Web/phalcon/demo/phpinfo.php 67 2020-08-28 15:09:40 (CEST) 2 Warning Invalid error type specified /Users/idcpj/Web/phalcon/demo/phpinfo.php 67 2020-08-28 15:09:40 (CEST) 2 Warning Invalid error type specified /Users/idcpj/Web/phalcon/demo/phpinfo.php 67 ``` ### 把错误转换为异常抛出(推荐) ``` set_error_handler("error_handler"); function error_handler($errno, $errstring, $errfile, $line, $trace) { throw new ErrorException($errstring, $errno, 0, $errfile, $line); } try { $c = 21 / 0; // 异常会正常抛出,不会被接收 //throw new Exception("asd"); } catch(ErrorException $e) { echo "自定义错误:".$e->getMessage(), "\n"; } ```
';