tags:

views:

18

answers:

2

Is it possible to remove the trace elements from the __toString.

What I want 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.

A: 

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();
    }
}
Nev Stokes
So does that mean with your method, that I would throw PDOExceptions without a try catch block to ensure that they are uncaught exceptions?
Shawn H
What's the point of displaying **any** error informations to the final user? Just show a typical "Application Error. Please try again (later)." message and save actual error to the log file.
Crozin
These are just examples, my project logs all errors and displays a generic message to the end user like you suggest
Shawn H
@Crozin During development error messages can be kind of useful ;)
Nev Stokes
Shawn, this is taken from a specific example where I want to ensure that whoever is using the class can't display connection details by forgetting to try catch but I guess you could leave off the restore and see how you get on. Bad practice though I'd have thought.
Nev Stokes
A: 

Something like this?

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