溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么用php寫(xiě)一個(gè)異常處理程序

發(fā)布時(shí)間:2021-09-06 17:18:28 來(lái)源:億速云 閱讀:109 作者:chen 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹“怎么用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í)用的文章!

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

php
AI