標籤:blog http io 使用 ar sp div art 問題
程式只要在運行,就免不了會出現錯誤!或早或晚,只是時間問題罷了。
錯誤很常見,比如Notice,Warning等等。此時一般使用set_error_handler來處理:
<?phpset_error_handler(function($errno, $errstr, $errfile, $errline) { var_dump($errno, $errstr, $errfile, $errline);});// Notice: Use of undefined constant strlenstrlen;// Warning: strlen() expects exactly 1 parameter, 0 givenstrlen();?>
具體能做些什麼呢?統一管理錯誤記錄檔,或者呈現一個相對友好的錯誤提示頁面等等。
但需要注意的是set_error_handler無法捕捉某些Fatal error,比如下面這個錯誤:
<?phpset_error_handler(function($errno, $errstr, $errfile, $errline) { var_dump($errno, $errstr, $errfile, $errline);});// Fatal error: Call to undefined function undefined_function()undefined_function();?>
不過我們真的就一點辦法都沒有了嗎?當然不是,我們不僅有辦法,而且還有好幾種:
第一種:ob_start + error_get_last
<?phpob_start(function($buffer) { if ($error = error_get_last()) { return var_export($error, true); } return $buffer;});// Fatal error: Call to undefined function undefined_function()undefined_function();?>
第二種:register_shutdown_function + error_get_last
<?phpregister_shutdown_function(function() { if ($error = error_get_last()) { var_dump($error); }});// Fatal error: Call to undefined function undefined_function()undefined_function();?>
此外,所有的Parse error(比如說少寫了分號之類的錯誤)都無法捕捉,不過換個角度看,解析錯誤的代碼本身就不應該發布,甚至都不應該進入版本庫,關於這一點,我以前寫過一篇《Subversion鉤子》,裡面介紹了如何利用Subversion鉤子做代碼語法檢查。
轉載自 http://huoding.com/2012/05/31/151
PHP中的錯誤處理