PHP 錯誤與異常 筆記與總結(17 )像處理異常一樣處理 PHP 錯誤
有兩種方式可以在 PHP 中以異常的方式處理錯誤:
① PHP 內建的 ErrorException 類(也是 Exception 類的子類)
1 php 2 function exception_error_handler($errno, $errstr, $errfile, $errline){ 3 throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 4 } 5 6 set_error_handler('exception_error_handler'); 7 8 try{ 9 //出發異常10 echo gettype();11 }catch(Exception $e){12 echo $e->getMessage();13 }
輸出:
用過這種方式把警告資訊以異常資訊輸出出來了。
② 自訂異常類來處理 PHP 中的錯誤
1 php 2 class ErrorToException extends Exception{ 3 public static function handler($errno, $errstr){ 4 throw new self($errstr, $errno); 5 } 6 } 7 8 set_error_handler(array('ErrorToException', 'handler')); 9 10 try{11 //觸發錯誤,未定義的變數,產生通知層級的錯誤12 echo $test;13 }catch(ErrorToException $e){14 echo $e->getMessage();15 }
輸出:
還可以使用 set_error_handler 設定錯誤層級:
1 php 2 class ErrorToException extends Exception{ 3 public static function handler($errno, $errstr){ 4 throw new self($errstr, $errno); 5 } 6 } 7 8 set_error_handler(array('ErrorToException', 'handler')); 9 //設定錯誤層級,例如只有警告層級的錯誤才以異常的形式進行捕獲10 set_error_handler(array('ErrorToException', 'handler'), E_USER_WARNING|E_WARNING);11 12 try{13 //觸發錯誤,未定義的變數,產生通知層級的錯誤14 echo $test;15 }catch(ErrorToException $e){16 echo $e->getMessage();17 }
輸出:
也就是說,通知層級的錯誤不交給自訂異常類來處理。
trigger_error 也能觸發異常:
1 php 2 header('content-type:text/html; charset=utf-8'); 3 4 class ErrorToException extends Exception{ 5 public static function handler($errno, $errstr){ 6 throw new self($errstr, $errno); 7 } 8 } 9 10 set_error_handler(array('ErrorToException', 'handler'));11 //設定錯誤層級,例如至喲喲警告層級的錯誤才以異常的形式進行捕獲12 set_error_handler(array('ErrorToException', 'handler'), E_USER_WARNING|E_WARNING);13 14 try{15 //觸發錯誤,未定義的變數,產生通知層級的錯誤16 echo $test;17 echo '';18 //gettype();19 echo '';20 trigger_error('test', E_USER_WARNING);21 }catch(ErrorToException $e){22 echo '異常';23 echo $e->getMessage();24 }
輸出: