donglongqiao9595 2012-10-02 20:04
浏览 52
已采纳

PDO“异常安全”并将其写入日志文件PHP

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?

  • 写回答

1条回答 默认 最新

  • doujishao8793 2012-10-02 20:09
    关注

    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);
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?