2009-12-27 68 views
3

當我的劇本開始,我有:爲什麼我的自定義錯誤處理程序未被調用?

error_reporting(E_ALL); 
ini_set('display_errors', TRUE); 
ini_set('display_startup_errors', TRUE); 

然後,我註冊了我的自定義錯誤處理程序與PHP:

function handleError($code, $text, $file, $line) { 
    echo "&%!!"; 
    return true; 
} 

set_error_handler('handleError'); 

下,總會有一些會產生這樣的錯誤代碼:

Fatal error: Call to undefined method DB::getInstanceForDB() in /Applications/MAMP/htdocs/mysite/classes/Test.php on line 32

我不斷地得到標準的PHP錯誤消息框與調用堆棧和我的網站上的所有內容,無論我是否指定自定義錯誤處理程序。任何想法有什麼不對?

編輯:無論我是否返回true,它都不會調用我的自定義處理函數。

回答

5

首先,你需要讓你的錯誤處理函數返回true。從set_error_handler

If the function returns FALSE then the normal error handler continues.

其次,要注意的是致命的錯誤不是由set_error_handler處理。您還需要使用register_shutdown_function。所以你的代碼應該是這樣的:

// Handles non-fatal errors 
function handleError($code, $text, $file, $line) { 
    var_dump($code); 
    return true; 
} 
set_error_handler('handleError'); 

// Handles fatal errors 
function fatalShutdown() { 
    var_dump(error_get_last()); 
} 
register_shutdown_function('fatalShutdown'); 
+0

看到有關致命錯誤的更新。 – philfreo 2009-12-27 21:01:01

0

在你的問題,你告訴你正在得到一個致命錯誤。

我不認爲你可以抓住那些,因爲它們......好......致命。

報價set_error_handler

The following error types cannot be handled with a user defined function: E_ERROR , E_PARSE , E_CORE_ERROR , E_CORE_WARNING , E_COMPILE_ERROR , E_COMPILE_WARNING , and most of E_STRICT raised in the file where set_error_handler() is called.

3

接受的答案是錯的,因爲關斷功能呼籲所有停產,包括那些在其他地方進行處理,或者只是當一個頁面成功完成。

我結束了這一點,除了使用set_exception_handler和的set_error_han dler:

// from http://www.php.net/manual/en/function.set-error-handler.php 
define('FATAL', E_ERROR | E_PARSE | E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_COMPILE_WARNING); 

register_shutdown_function('shutdown'); 

// Handles "fatal" errors e.g. Syntax errors 
function shutdown() { 
    // Only if there was an fatal error, this is run on all execution endpoints 
    $error_info = error_get_last(); 
    if ($error_info !== null && ($error_info['type'] & FATAL)) { 
     # stack trace set to empty array, as generating one here is useless 
     [[ do stuff like emailing someone]] 
    } 
} 
相關問題