php實現例項化類後自動進行錯誤以及異常處理(簡易版)
阿新 • • 發佈:2018-12-26
<?php class App { public function __construct() { /* * ini_set 設定配置項 * display_errors 是否在頁面顯示錯誤資訊 */ ini_set('display_errors', 0); $this->setSysHandler(); } public function setSysHandler() { //php中止時執行 register_shutdown_function([$this, 'fatalHandler']); //設定使用者自定義的錯誤處理函式 set_error_handler([$this, 'errorHandler']); //設定使用者自定義的異常處理函式 set_exception_handler([$this, 'exceptionHandler']); } // 錯誤被包裝成為異常丟擲 public function errorHandler($code, $msg, $file, $line) { throw new ErrorException($msg, $code, $code, $file, $line); } public function fatalHandler() { if ($errors = error_get_last()) { $msg = $errors['message']; $code = $errors['type']; $file = $errors['file']; $line = $errors['line']; echo "<font size='7'>:(</font><h2> 檔案: {$file}; 行號: {$line};</h2>"; echo "<h4>錯誤資訊: {$msg}; 錯誤程式碼: {$code}</h4>"; echo "<pre>"; } } public function exceptionHandler($excep) { $this->handler($excep); } public function handler($excep) { $msg = $excep->getMessage();//獲取異常訊息內容 $code = $excep->getCode();//獲取異常程式碼 $file = $excep->getFile();//建立異常時的程式檔名稱 $line = $excep->getLine();//獲取建立的異常所在檔案中的行號 $trace = $excep->getTrace();//獲取異常追蹤資訊 $this->errorlog($msg, $code, $file, $line);//傳送錯誤資訊到某個地方 echo "<font size='7'>:(</font><h2> 檔案: {$file}; 行號: {$line};</h2>"; echo "<h4>錯誤資訊: {$msg}; 錯誤程式碼: {$code}</h4>"; echo "<pre>"; if ($excep instanceof ErrorException) { array_shift($trace); } print_r($trace); //函式的呼叫棧 } public function errorlog($msg, $code, $file, $line) { $str = date('Y-m-d H:i:s') . "\r\n"; $str .= "錯誤資訊是:"; $str .= $msg; $str .= "\r\n"; $str .= "錯誤行號是:"; $str .= $line; $str .= "\r\n"; $str .= "錯誤程式碼是:"; $str .= $code; $str .= "\r\n"; $str .= "錯誤行檔案:"; $str .= $file; $str .= "\r\n"; $str .= "\r\n"; error_log($str, 3, './myerror.log'); } } $app = new App();