PHP的異常捕捉與運行特殊處理
1.php的錯誤捕獲:try{} catch(Exception $e) { echo $e->getMessage();}句型格式對于錯誤的調試和控制幫助是非常大的。
<?php
class test {
static public function atest($val) {
if($val>1) throw new Exception("Parms greater than 1");
if($val<1&&$val>0) throw new Exception("error");
echo $val;
}
}
try {
$val = 0.5;
test::atest($val);
} catch (Exception $e) {
exit(json_encode(array("err_code"=>"500","err_msg"=>$e->getMessage())));
}
?> 優勢:主要用來捕獲系統級的錯誤(業務邏輯層面的錯誤一般不用捕獲)這樣避免了方法的污染
ps:捕獲可以獲取到的信息包括getFile() 獲取文件 getLine()獲取出錯的行 getMessage() 獲取插入的提示報錯信息。框架機制中,一般都需要提供捕獲機制
2.如果不用try{}catch(Exception $e){}句型
PHP里提供了一個set_exception_handler()的簡化寫法
<?php
function test1($e) {
echo $e->getMessage();
}
set_exception_handler('test1');
throw new Exception("test");
?> 3.另外一個錯誤提示的函數(和set_exception_handler()相似的用法)
<?php
function test() {
echo " XPHP notice error";
}
set_error_handler("test");
test
?> 該段代碼會報錯XPHP notice error
set_error_handler(error_function,error_types)
參數 描述
error_function 必需。規定發生錯誤時運行的函數。
error_types 可選。規定在哪個錯誤報告級別會顯示用戶定義的錯誤。默認是 "E_ALL"。
4.另外一個常用到的框架函數
register_shutdown_function('endRecord');
腳本運行完成后需要記錄的動作
<?php
function endRecord() {
echo "PHP Script End";
}
register_shutdown_function('endRecord');
?>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!