2015-05-07 41 views
0

我正在從事網絡服務。嘗試catch不工作在PHP?

我在試圖捕捉錯誤。我的問題代碼是:

try 
    { 
    $query = "UPDATE Users 
       SET 
       Latitude=?, 
       Longitude=?, 
       Address=?, 
       LocationTimestamp=? 
       WHERE Id=?"; 

     $stmt = $this->link->prepare($query); 
     $stmt->bind_param('ddssi', $Latitude, $Longitude, $Address, $LocationTimestamp, $Id); 
     $stmt->execute(); 


     $affected_rows = $stmt->affected_rows; 

    } 

    catch(Exception $exc) 
    { 
     file_put_contents("log/error.txt",$exc->getMessage()); 
    } 

我預料,catch塊會捕獲所有錯誤,並且PHP不會在輸出中產生任何錯誤。然而 - 輸出我看到這樣的事情:

警告:在 /srv/webservice/server.php創建默認的對象從空值就行

我想避免輸出任何HTML,因爲這是Web服務,我在客戶端有JSON解釋器。

我的問題是:

如何調試服務這樣的,當我必須PHP輸出進不去?我想將所有錯誤,警告等重定向到文件。

回答

1

你得到一個PHP的警告,也不例外。也許這有助於直接保存你的錯誤:

ini_set("log_errors", true); 
ini_set("error_log", "log/error.txt"); 

這將記錄所有的PHP錯誤和警告(和通知)到這個文件中。

代碼塊後,您可以禁用它,如果你想這樣:

ini_set("log_errors", false); 
2

警告不是一個例外.....你可以捕捉異常,但不是警告/聲明/錯誤/等。如果你想警告你開捕需要將它們轉換爲與用戶定義的錯誤處理程序使用的例外

class MyCustomException extends Exception { 
    public static function errorHandlerCallback($code, $string, $file, $line, $context) { 
     $e = new self($string, $code); 
     $e->line = $line; 
     $e->file = $file; 
     throw $e; 
    } 
} 

set_error_handler(['MyCustomException', 'errorHandlerCallback'], E_ALL); 
+0

也許還值得一說的是,你可以打開輸出緩衝,然後使用'error_get_last()'來獲得如果發生了最後的錯誤。並將警告轉換爲異常,這可能是相關的:http://stackoverflow.com/q/1241728/3933332 – Rizier123