PHP错误处理程序和ErrorException混淆:日志堆栈跟踪

时间:2014-04-18 10:11:19

标签: php exception-handling error-handling

我想将所有PHP错误记录到数据库中,所有这些都有堆栈跟踪。但PHP Manual代码段让我困惑:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

我目前使用传递给`set_error_handler()'的函数将错误记录到数据库中。但是,如果我使用上面的代码,我在哪里将编写错误和堆栈跟踪的代码放到数据库中?

function error_handler($errno, $errstr, $errfile, $errline){
    $err = array(
        'errno' => $errno,
        'errstr' => $errstr,
        'errfile' => $errfile,
        'errline' => $errline
    );
    DB::insertAssoc('table_error', $err);
}

1 个答案:

答案 0 :(得分:2)

使用“例外”时,您需要使用try {/* code */} catch (Exception $error) {/* handle exception code*/}。试试这个:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

function error_handler($errno, $errstr, $errfile, $errline){
    $err = array(
            'errno' => $errno,
            'errstr' => $errstr,
            'errfile' => $errfile,
            'errline' => $errline
    );

    DB::insertAssoc('table_error', $err);
}

set_error_handler("exception_error_handler");

try {
    $q/1;
} catch (ErrorException $e) {
    error_handler(
        $e->getSeverity(),
        $e->getMessage(),
        $e->getFile(),
        $e->getLine()
    );
}

您可以在此处阅读有关使用Php中的例外处理的更多信息:http://www.php.net/manual/en/language.exceptions.php