2

I am writing a PDO wrapper and having this issue with catching exceptions.

I am trying to maintain exception safety practice,so I wanted to know how to catch an exception,writing it to a log file,and using exception safety to to do something, probably tell the user to retry action again or navigate to an error page or whatever (anything you can suggest).

So how is it done if possible?

4

1 回答 1

4

Look at this code snippet, it shows how it is done:

class MyDb extends PDO 
{
  protected $error;

  function __construct( $logger )
  {
    try {
      parent::__construct( 'mysql:host=localhost;dbname=xxxx', 'xxx', 'xxx' );
      $this->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );

    }
    catch ( Exception $e ) {
       $this->error = $e->getMessage();
       // do your log writing stuff here
       $logger->Add( $this->error ); 
    }
  }
}

update:

usage of the class:

$logger = new MyLogger();
$db = new MyDb( $logger );

of course, you need a logger class with a add method:

class MyLogger
{
  const FILENAME = '/tmp/mylog.txt' ;

  function Add( $error )
  {
    file_put_contents( self::FILENAME, $error, FILE_APPEND);
  }
}
于 2012-10-02T20:09:52.957 回答