PHP中的錯誤處理

來源:互聯網
上載者:User

標籤: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中的錯誤處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.