当前位置: 首页 > 后端技术 > PHP

PHP捕获错误

时间:2023-03-30 05:32:00 PHP

PHP捕获错误并禁用错误输出error_reporting(0);设置错误处理程序set_error_handler('errorHandler');在脚本结束时运行的函数register_shutdown_function('fatalErrorHandler');错误处理/***@paramint$err_no错误代码*@paramstring$err_msg错误信息*@paramstring$err_file错误文件*@paramint$err_line错误行号*@returnstring*/functionerrorHandler($err_no=0,$err_msg='',$err_file='',$err_line=0){$log=['['.date('Y-m-dh-i-s').']','|',$err_no,'|',$err_msg,'|',$err_file,'|',$err_line];$log_path='./test.txt';error_log(implode('',$log)."\r\n",3,$log_path);}捕获致命错误函数fatalErrorHandler(){$e=error_get_last();var_export($e);switch($e['type']){案例1:errorHandler($e['type'],$e['message'],$e['file'],$e['line']);休息;}}classDemoClass_1{publicfunctionindex(){//这里出现警告错误,启动errorHandlerecho$undefinedVari祝福;}}这里出现警告错误,被errorHandler$demo_1=newDemoClass_1();捕获到$demo_1->index();发生致命错误,脚本停止运行并触发fatalErrorHandler$demo_2=newDemoClass_2();$demo_2->索引();打开test.txt后输出:[2018-06-1205-49-11]|8|未定义变量:undefinedVarible|/用户/darry/htdocs/test.php|57[2018-06-1205-49-11]|1|未捕获的错误:在/Users/darry/htdocs/test.php:67Stacktrace:#0{main}中找不到类'DemoClass_2'/用户/darry/htdocs/test.php|67