2009-12-27 60 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]] 
    } 
} 
相关问题