我目前对于 PDO 有点进退两难。我最近转而从我自己的自定义数据库类中使用它,因为我想利用事务。我面临的问题是如何从已经用 PDO 的 try/catch 包装的代码块内部抛出异常。这是一个例子...
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
}
采用上面的代码示例并记住 PHP 手册中的内容: “你不应该从你自己的代码中抛出 PDOException”。我将如何处理自己的异常andPDO 的?某种筑巢?
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
}
问题是,你将会有重复的代码,而且味道不太好。我建议只捕获“异常”,例如:
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)