PHP, PDO, and Exceptions

南楼画角 提交于 2019-12-23 16:49:00

问题


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 handle my own exceptions and the PDO ones? Some kind of nesting?


回答1:


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
}



回答2:


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



回答3:


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(....);


来源:https://stackoverflow.com/questions/7188167/php-pdo-and-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!