我目前对 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”。我将如何处理我自己的异常和 PDO 异常?某种嵌套?
最佳答案
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
}
关于PHP、PDO 和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7188167/