开发者

PHP, PDO, and Exceptions

I'm currently in a bit of a dilemma regarding PDO. I've recently switched to using it from my own custom database class as I want to take advantage of transactions. The problem I'm facing is how to throw exceptions from inside a block of code that is already wrapped with try/catch for PDO. Here is an example...

try {
    // PDO code

    // Transaction start

    // Throw manual exception here if error occurs (transaction rollback too)

   // Transaction commit

} catch (PDOException $e) {
    // Transaction rollback
    // Code to handle the exception
}

Taking the above code example and bearing in mind that the PHP manual says; "You should not throw a PDOException from your own code". How would I handl开发者_运维百科e my own exceptions and the PDO ones? Some kind of nesting?


try {
    // PDO code

    // Transaction start

    // Throw manual exception here if error occurs (transaction rollback too)
    throw new MyException("all went tits up");

   // Transaction commit

} catch (PDOException $e) {
    // Transaction rollback
    // Code to handle the exception
} catch (MyException $e) {
    // Transaction rollback
    // Code to handle the exception   
}

The thing is, you're going to have duplicate code which wont smell too nice. I would recommend just catching "Exception" e.g.:

try {
    // PDO code

    // Transaction start

    // Throw manual exception here if error occurs (transaction rollback too)
    throw new MyException("all went tits up");

   // Transaction commit

} catch (Exception $e) {
    // Transaction rollback
    // Code to handle the exception
}


try{
    //code here
}
catch(PDOException $e){
    //handle PDO
    throw $e; //to rethrow it upper if need
}
catch(Exception $e){
    //handle any other
}


If something is going wrong PDO will generate exception. But if you make some changes in db and would like to revert all you can run

throw new PDOException(....);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜