您好,登錄后才能下訂單哦!
這篇文章主要介紹“怎么用php寫(xiě)一個(gè)異常處理程序”,在日常操作中,相信很多人在怎么用php寫(xiě)一個(gè)異常處理程序問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”怎么用php寫(xiě)一個(gè)異常處理程序”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
直接上代碼
<?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')){ /** * 當(dāng)發(fā)生重大錯(cuò)誤時(shí) 寫(xiě)日志 并友好提示用戶 * (PS:只所以將代碼寫(xiě)在這里,是因?yàn)樵谄渌胤阶?cè)時(shí),出現(xiàn)問(wèn)題無(wú)法調(diào)用配置函數(shù).待完善...) */ function shutdownHandler() { /** * 寫(xiě)日志 此處直接寫(xiě)在根目錄下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('對(duì)不起,我出錯(cuò)了!'); } } register_shutdown_function('shutdownHandler'); } if(!defined('DEBUG')){ function errorHandler($errno, $errstr = '', $errfile = '', $errline = 0) { //寫(xiě)日志 $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) { //獲取最準(zhǔn)確的異常 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寫(xiě)一個(gè)異常處理程序”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。