2010-10-05 41 views
1

是否可以從__toString中刪除跟蹤元素。從PDOException __toString方法中刪除跟蹤信息的最佳方法

我想要的是這樣的。

class DBException extends PDOException 
{ 
public function __toString() 
{ 
    return get_class($this) . " '{$this->getMessage()}' in {$this->getFile()}({$this->getLine()})\n"; 
} 
} 

我試過上面的方法,但它似乎沒有工作。有任何想法嗎?

如果我以下面的try catch塊爲例,我仍然會得到跟蹤數據。

try { 

// Do something here 

}catch(DBException $e) { 
    echo $e; 

} 

我會想到echo $ e會觸發我的DBException類中的__toString方法。

+1

請解釋*似乎不工作* – Gordon 2010-10-05 08:01:49

回答

0

當我想用PDO處理異常(在這種情況下,爲了確保連接細節不會顯示給用戶),我過去所做的是擴展PDO類並簡單地更改異常處理程序:

class extendedPDO extends PDO 
{ 
    public static function exception_handler(Exception $exception) 
    { 
     // Output the exception details 
     die('<h1>Database connection error<p>' . $exception->getMessage() . '</p>'); 
    } 

    public function __construct($dsn, $username=null, $password=null, $options=array()) 
    { 
     // Temporarily change the PHP exception handler while we . . . 
     set_exception_handler(array(__CLASS__, 'exception_handler')); 

     // Create PDO 
     parent::__construct($dsn, $username, $password, $options); 

     // Change the exception handler back to whatever it was before 
     restore_exception_handler(); 
    } 
} 
+0

這是否與你的方法是說,我會扔PDOExceptions沒有try catch塊,以確保它們捕獲的異常? – 2010-10-05 16:07:24

+0

向最終用戶顯示**任何**錯誤信息有什麼意義?只顯示一個典型的「應用程序錯誤,請重試(稍後)。」消息並將實際錯誤保存到日誌文件。 – Crozin 2010-10-05 16:12:10

+0

這些只是一些例子,我的項目記錄了所有錯誤,並向終端用戶顯示一條通用消息,如你所建議 – 2010-10-05 16:18:03

0

是這樣的?

public function __toString() { 
    $return = "Class: ".get_class($this) 
      ."\nMessage: ".$this->getMessage() 
      ."\nFile: ".$this->getFile() 
      ."\nLine: ".$this->getLine()."\n"; 
    return $return; 
} 
相關問題