分享一個php 的異常處理程序
更新時間:2014年06月22日 11:01:21 投稿:hebedich
給大家分享一個php的異常處理程序,功能很簡單當發(fā)生重大錯誤時,寫日志并友好提示用戶,用處卻很大,對不對
直接上代碼
<?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')){ /** * 當發(fā)生重大錯誤時 寫日志 并友好提示用戶 * (PS:只所以將代碼寫在這里,是因為在其他地方注冊時,出現(xiàn)問題無法調(diào)用配置函數(shù).待完善...) */ function shutdownHandler() { /** * 寫日志 此處直接寫在根目錄下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); //友好提示用戶 ob_end_clean(); die('對不起,我出錯了!'); } } register_shutdown_function('shutdownHandler'); } if(!defined('DEBUG')){ function errorHandler($errno, $errstr = '', $errfile = '', $errline = 0) { //寫日志 $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) { //獲取最準確的異常 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'); } ?>
相關(guān)文章
php 使用fopen函數(shù)創(chuàng)建、打開文件詳解及實例代碼
這篇文章主要介紹了php 使用fopen函數(shù)創(chuàng)建、打開文件詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下2016-09-09從零開始學YII2框架(四)擴展插件yii2-kartikgii
yii2-kartikgii這個插件主要功能是幫助你在使用gii生成代碼curd的時候生成kartik-gird的。不需要每次用默認的gii工具生成代碼之后再手動添加kartik-gird,這正是我想要的功能??焖偕蒶artik-grid。2014-08-08windows7配置Nginx+php+mysql的詳細教程
這篇文章主要介紹了windows7配置Nginx+php+mysql的詳細教程 的相關(guān)資料,需要的朋友可以參考下2016-09-09php無法連接mysql數(shù)據(jù)庫的正確解決方法
這篇文章主要為大家詳細介紹了php無法連接mysql數(shù)據(jù)庫的正確解決方法,感興趣的小伙伴們可以參考一下2016-07-07php中對內(nèi)置函數(shù)json_encode和json_decode的異常處理
這篇文章主要介紹了php中對內(nèi)置函數(shù)json_encode和json_decode的異常處理,本篇文章通過定義描述和列舉表格以及最后代碼的展示,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07深入剖析瀏覽器退出之后php還會繼續(xù)執(zhí)行么
覽器退出之后php還會繼續(xù)執(zhí)行么?下面小編就為大家介紹一下究竟覽器退出之后php還會不會繼續(xù)執(zhí)行。一起跟隨小編過來看看吧2016-05-05ThinkPHP 3.2.3實現(xiàn)加減乘除圖片驗證碼
這篇文章主要為大家詳細介紹了ThinkPHP 3.2.3實現(xiàn)加減乘除圖片驗證碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12