Cri*_*spy 3 php pdo exception-handling
我目前处于PDO的两难境地.我最近转而使用自己的自定义数据库类,因为我想利用事务.我面临的问题是如何从已经用try/catch for PDO包装的代码块中抛出异常.这是一个例子......
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
}
Run Code Online (Sandbox Code Playgroud)
以上面的代码示例为例,记住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
}
Run Code Online (Sandbox Code Playgroud)
问题是,你将会有重复的代码,它们闻起来不太好.我建议只捕捉"例外",例如:
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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |