錯誤報告關閉和打開
php.ini 的 display_errors = On 或者 Off
代碼里 ini_set(‘display_errors’,1) 或者 0
錯誤報告級別

最佳實踐
開發環境下打開錯誤報告,并且錯誤報告級別 E_ALL
正式環境一定要關閉錯誤報告
//顯示所有的錯誤型別 error_reporting(E_ALL); //顯示所有的錯誤型別,除了NOTICE 提示之外 error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL &~ E_NOTICE); //關閉所有的PHP錯誤報告 error_reporting(0); //報告所有的錯誤型別 error_reporting(-1);
舉例
try { //找不到檔案 throw new Exception('找不到檔案',1); //沒有權限訪問 throw new Exception('沒有權限',2); } catch (Exception $e) { $errno = $e -> getCode(); if($errno == 1){ echo $e -> getFile(); }elseif($errno == 2){ echo $e -> getLine(); } }
檔案例外類
class FileException extends Exception{ public function fileInfo(){ return $this->getMessage(); } } try { print "open file"; throw new FileException('file does not exist'); } catch (Exception $e) { print $e -> fileInfo(); }
捕獲多個例外
class FileException extends Exception{} //檔案不存在的例外 class FileNotExistException extends FileException{} //檔案權限例外 class FilePermissionException extends FileException{} function fileHandle(){ //檔案不存在 throw new FileNotExistException('file does not exist'); //檔案權限例外 throw new FilePermissionException('access denied'); //其他例外 throw new FileException('other exception'); } try { fileHandle(); } catch (FileNotExistException $e) { echo $e -> getMessage(); }catch(FilePermissionException $e){ echo $e -> getMessage(); }catch(FileException $e){ echo $e -> getMessage(); }
全域例外處理
<?php class FileException extends Exception{ //檔案不存在 const FILE_NOT_EXIST = 1; //權限不夠 const FILE_PERMISSION = 2; } function fileHandle(){ //檔案不存在 throw new FileException('FilenotExist',FileException::FILE_NOT_EXIST); //權限不夠 throw new FileException('FilePermission',FileException::FILE_PERMISSION); } try { fileHandle(); } catch (Exception $e) { switch ($e -> getCode()) { case FileException::FILE_NOT_EXIST: echo($e->getMessage()); break; case FileException::FILE_PERMISSION: echo ($e -> getMessage()); break; } }catch(Exception $e){ echo 'exception'; } ?> ------------------------------------------ <?php function defaultExceptionHandle($e){ printf("uncaught exception:%s in file %s on line %d",$e->getMessage(),$e->getFile(),$e->getLine()); } set_exception_handler('defaultExceptionHandle'); throw new Exception('tese......'); ?>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/86766.html
標籤:PHP
上一篇:PHP 限制訪問ip白名單
下一篇:51N皇后
