1.什麼是異常?異常和錯誤有什麼區別?
1.異常:程式運行與預期不太一致,與錯誤是兩個不同的概念!
2.拋出和捕獲異常
3.多個catch塊的時候基類要往後放,否則基類捕獲異常後就不會往下繼續捕獲了!
3.先出現錯誤,在出現異常,所以寫api的時候一定要把display_errors關掉
4.php的內建異常
error_reporting(-1);ini_set('display_errors','off');//pdo內建異常類try { $pdo = new PDO('mysql:host=localhost;dbname=mysql', 'brave', '123456'); var_dump($pdo); echo ''; echo 'continue.......';} catch (Exception $e) { echo $e->getMessage();}echo 'this is a test.......';echo '';//spl檔案讀寫內建異常類try { $splObj = new SplFileObject('test.txt', 'r'); echo 'read file';} catch (RuntimeException $e) { echo $e->getMessage();}echo 'continue.......';echo '';
2.異常的基本文法結構
try { //需要進行異常處理的代碼 throw語句拋出 } catch (PdoException $e) { try { throw語句拋出 } catch (Exception $e) { } } catch (FileException $e) { } catch (CustomException $e) { } //other code
3.如何自訂異常類?
error_reporting(-1);ini_set('display_errors','off');class MyException extends Exception{ function __construct($message, $code=0) { parent::__construct($message, $code); } public function __toString(){ $message = "出現異常了,資訊如下
"; $message .="".__CLASS__." [{$this->code}]:{$this->message}
"; return $message; } public function test(){ echo 'this is a test'; } public function stop(){ exit('script end..............'); } //自訂其他方法}try { echo '出現異常了!'; throw new MyException("測試自訂異常!", 11);} catch (MyException $e) { echo $e->getMessage(); echo ''; echo $e; echo ''; $e->stop(); $e->test();}
4.自訂檔案異常類
error_reporting(-1);ini_set('display_errors','off');class FileException extends Exception { public function getDetails() { switch ($this->code) { case 0: return '沒有提供檔案!'; break; case 1: return '檔案不存在!'." trace".$this->getTraceAsString().$this->getLine(); break; case 2: return '不是一個檔案!'." trace".$this->getTraceAsString().$this->getLine(); break; case 3: return '檔案不可寫!'; break; case 4: return '非法檔案的操作模式!'; break; case 5: return '資料寫入失敗!'; break; case 6: return '檔案不能被關閉!'; break; default: return '非法!'; break; } }}class WriteData{ private $_message=''; private $_fp=null; public function __construct($filename=null, $mode='w'){ $this->_message="檔案:{$filename} 模式:{$mode}"; if (empty($filename)) { throw new FileException($this->_message, 0); } if (!file_exists($filename)) { throw new FileException($this->_message, 1); } if (!is_file($filename)) { throw new FileException($this->_message, 2); } if (!is_writable($filename)) { throw new FileException($this->_message, 3); } if (!in_array($mode, array('w', 'w+', 'a', 'a+'))) { throw new FileException($this->_message, 4); } $this->_fp=fopen($filename, $mode); } /** * [write 寫資料] * @param [type] $data [description] * @return [type] [description] */ public function write($data){ if (@!fwrite($this->_fp, $data.PHP_EOL)) { throw new FileException($this->_message, 5); } } /** * [close 關閉檔案控制代碼] * @return [type] [description] */ public function close(){ if ($this->_fp) { if (@!fclose($this->_fp)) { throw new FileException($this->_message, 6); $this->_fp=null; } } } public function __destruct(){ $this->close(); }}try { $fp = new WriteData('test.txt', 'w'); $fp->write('this is a test'); $fp->close(); echo '資料寫入成功!';} catch (FileException $e) { echo '出問題了:'.$e->getMessage().' 詳細資料如下:'.$e->getDetails();}
5.使用觀察者模式處理異常
- 定義觀察(異常)的類, 可以在代碼中動態添加觀察者
/** * 觀察(異常)的類, 可以在代碼中動態添加觀察者 */ class Observable_Exception extends Exception { public static $_observers=array(); public static function attach(Exception_Observer $observer){ self::$_observers[]=$observer; } public function __construct($message=null, $code=0){ parent::__construct($message, $code); $this->notify(); } public function notify(){ foreach (self::$_observers as $observer) { $observer->update($this); } } }
2.定義異常觀察者基類,用於規範每一個觀察者
/** * 觀察者基類,用於規範每一個觀察者 */ interface Exception_Observer{ //強制指定必須是我們規定的觀察類 public function update(Observable_Exception $e); }
3.定義日誌觀察者
/** * 定義日誌觀察者 */ class Logging_Exception_Observer implements Exception_Observer{ public $_filename='./log_exception.log'; public function __construct($filename=null){ if ($filename!==null && is_string($filename)) { $this->_filename=$filename; } } public function update(Observable_Exception $e){ $message="時間:".date('Y-m-d H:i:s').PHP_EOL; $message.="資訊:".$e->getMessage().PHP_EOL; $message.="追蹤資訊:".$e->getTraceAsString().PHP_EOL; $message.="檔案:".$e->getFile().PHP_EOL; $message.='行號:'.$e->getLine().PHP_EOL; error_log($message, 3, $this->_filename); } }
4.定義郵件觀察者
/** * 定義郵件觀察者 */ class Email_Exception_Observer implements Exception_Observer{ public $_email='732578448@qq.com'; public function __construct($email=null){ if ($email!==null && filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->_email=$email; } } public function update(Observable_Exception $e){ $message="時間:".date('Y-m-d H:i:s').PHP_EOL; $message.="資訊:".$e->getMessage().PHP_EOL; $message.="追蹤資訊:".$e->getTraceAsString().PHP_EOL; $message.="檔案:".$e->getFile().PHP_EOL; $message.='行號:'.$e->getLine().PHP_EOL; error_log($message, 1, $this->_email); } }
5.執行測試
error_reporting(-1);ini_set('display_errors','off');//引入觀察異常的類require 'Observable_Exception.php';//引入觀察者基類require 'Exception_Observer.php';//引入日誌觀察者require 'Logging_Exception_Observer.php';//引入郵件觀察者require 'Email_Exception_Observer.php';Observable_Exception::attach(new Logging_Exception_Observer());//自訂地址記錄錯誤異常Observable_Exception::attach(new Logging_Exception_Observer('/tmp/test11.log'));Observable_Exception::attach(new Email_Exception_Observer());//自訂郵件接收人記錄錯誤異常Observable_Exception::attach(new Email_Exception_Observer('123456@qq.com'));class MyException extends Observable_Exception{ public function test(){ echo 'this is a test!'; } public function test1(){ echo '我是 自訂的方法處理這個異常!'; }}try { throw new MyException("出現異常了,記錄一下下!");} catch (MyException $e) { echo $e->getMessage(); echo ''; $e->test(); echo ''; $e->test1();}
6.自訂異常處理器(set_exception_handler)?
1.目的1處理所有未捕獲的異常
2.目的2處理所有我們為放到try catch中的異常
3.自訂異常處理函數
ini_set('display_errors','off');function exceptionHandler_1($e){ echo '自訂異常處理器1'.__FUNCTION__; echo '異常資訊:'.$e->getMessage();}function exceptionHandler_2($e){ echo '自訂異常處理器2'.__FUNCTION__; echo '異常資訊:'.$e->getMessage();}set_exception_handler('exceptionHandler_1');set_exception_handler('exceptionHandler_2');//恢複到上一次定義過的異常處理函數restore_exception_handler();throw new Exception('測試');echo 'continue........';echo '';
4.自訂異常處理類
/** * 自訂錯誤異常類 */class ExceptionHandler{ protected $_exception; protected $_logFile='./testExceptionHandler.log'; function __construct(Exception $e){ //儲存異常對象 $this->_exception = $e; } public static function handle(Exception $e){ $self = new self($e); $self->log(); echo $self; } public function log(){ $msg=<<_exception->getFile()}
產生通知的資訊:{$this->_exception->getTraceAsString()} 產生通知的行號:{$this->_exception->getLine()} 產生通知的錯誤號碼:{$this->_exception->getCode()} 產生通知的時間:{$datetime} \n EOF; echo $msg; error_log($msg, 3, $this->_logFile); } public function __toString(){ $message = << 出現異常了。。。。。
重新整理下試試
EOF; return $message; }}ini_set('display_errors','off');set_exception_handler(array('ExceptionHandler', 'handle'));//放在try catch中的throwtry { throw new Exception("this is a test!",20010);} catch (Exception $e) { echo $e->getMessage();}//沒放在try catch中的throwthrow new Exception("測試未捕獲的自訂的異常處理器hello world!",2008);
7.如何像處理異常一樣處理PHP的錯誤?
1.通過ErrorException
function exception_error_handler($errno, $errstr, $errfile, $errline){ throw new ErrorException($errstr, 0, $errno, $errfile, $errline);}set_error_handler('exception_error_handler');try { echo gettype();} catch (Exception $e) { echo $e->getMessage();}
2.自訂異常類
class ErrorToException extends Exception{ public static function handle($errno, $errstr) { throw new self($errstr, $errno); }}ini_set('display_errors', 'off');set_error_handler(array('ErrorToException', 'handle'));set_error_handler(array('ErrorToException', 'handle'),E_USER_WARNING|E_WARNING);try { echo $test; gettype(); trigger_error('test',E_USER_WARNING);} catch (Exception $e) { echo $e->getMessage();}
8.在發生錯誤的時候將使用者重新導向到另一個頁面
class ExceptionRedirectHandler{ protected $_exception; protected $_logFile='./redirectLog.log'; protected $_redirect='404.html'; public function __construct(Exception $e){ $this->_exception=$e; } public static function handle(Exception $e){ $self = new self($e); $self->log(); while (@ob_end_clean()); header('HTTP/1.1 307 Temporary Redirect'); header('Cache-Control:no-cache,must-revalidate'); header('Expires: Wed, 01 Jul 2015 07:40:45 GMT'); header('Location:'.$self->_redirect); exit(1); } public function log($value=''){ error_log($this->_exception->getMessage().PHP_EOL, 3, $this->_logFile); }}ini_set('display_errors','off');set_exception_handler(array('ExceptionRedirectHandler', 'handle'));$link = mysql_connect('localhost', 'brave', '123456123');if (!$link) { throw new Exception("資料庫受到攻擊了,趕快去看看吧!");}
9.設定自訂錯誤和異常需要傳遞的參數
異常傳遞:$msg, $code
錯誤傳遞:$errno, $errmsg, $errfile, $errline 可看MyErrorHandler.php
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。