2017-05-05 37 views
0

所有錯誤,我想記錄由PHP數據庫拋出的所有錯誤。我如何獲得變量中的所有錯誤。PHP登錄拋出

在以下代碼中,未聲明的$ a已打印。但它沒有抓住。

$error = ""; 
try 
{ 
    echo $a; // not declared 
} 
catch(Exception $e) 
{ 
    $error = $e->getMessage(); 
} 

輸出

Notice (8): Undefined variable: a [APP\Controller\CronJobsController.php, line 71] 
+0

當你打印'$ error'時,你會得到什麼? – Akintunde007

+0

我認爲這可以幫助:輸出所有的PHP錯誤數據庫不error_log中(http://stackoverflow.com/questions/2911094/outputting-all-php-errors-to-database-not-error-log) –

+0

做你使用['set_error_handler()'](https://www.w3schools.com/php/func_error_set_error_handler.asp)? –

回答

1

的通知也不例外,因此它不能在Try {}捕捉{}塊被捕獲。與警告類似。

一般來說一個更好的主意,有讓他們顯示那些在你的開發環境的error_reporting級別,你不得不處理這些問題,你的代碼的方式。

然而,捕捉它們,對付它們的另一種方式,你要設置自定義錯誤處理程序。您可以讓您的自定義錯誤處理程序僅捕獲某些錯誤。

<?php 
// set custom handler for NOTICES 
// $oldHandler will allow you to reset the handler back to PHP default later 
$oldHandler = set_error_handler('myErrorHandler', E_NOTICE|E_WARNING); 

function myErrorHandler($errno, $errstr, $errfile, $errline) { 

    // log to DB in here 
    // $db->query("INSERT INTO error_log (errno, errstr...) VALUES (...)"); 

    // return false to let the error bubble up and get caught by default error handler 
    // return false; 

    // return true to tell PHP you've dealt with it 
    return true; 
} 

// YOUR SAMPLe CODE SHOULD NOW CAPTURE THE NOTICE 
$error = ""; 

try 
{ 
    echo $a; // not declared 
} 
catch(\Error $e) 
{ 
    $error = $e->getMessage(); 
} 

?> 
+0

其實我使用cakephp框架。任何方式在類的函數中記錄錯誤 –