Best way to remove the trace information from the PDOException __toString method
Is it possible to remove the trace elements from the __toString.
What I want 开发者_Go百科is something like this.
class DBException extends PDOException
{
public function __toString()
{
return get_class($this) . " '{$this->getMessage()}' in {$this->getFile()}({$this->getLine()})\n";
}
}
I've tried the above method but it doesn't seem to work. Any ideas?
If I use a try catch block below as example, I still get the trace data.
try {
// Do something here
}catch(DBException $e) {
echo $e;
}
I would have thought that echoing $e would trigger the __toString method in my DBException class.
What I've done in the past when I want to process an Exception with PDO (in this case to ensure that connection details aren't displayed to the user) is to extend the PDO class and change the exception handler briefly:
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();
}
}
Something like this?
public function __toString() {
$return = "Class: ".get_class($this)
."\nMessage: ".$this->getMessage()
."\nFile: ".$this->getFile()
."\nLine: ".$this->getLine()."\n";
return $return;
}
精彩评论