PHP,PDO和异常 [英] PHP, PDO, and Exceptions
问题描述
try {
// PDO code
/ / transaction start
//如果发生错误(如果出现错误,则抛出手动异常)
//事务提交
} catch(PDOException $ e){
//事务回滚
//处理异常的代码
}
考虑到上述代码示例,并铭记PHP手册; 你不应该从你自己的代码中抛出一个PDOException。我将如何处理我自己的例外情况? PDO?某种嵌套?
try {
// PDO code
//事务开始
//如果发生错误(如果发生错误,则抛出手动异常)
throw new MyException(all go tits up);
//交易提交
} catch(PDOException $ e){
//事务回滚
//处理异常的代码
} catch(MyException $ e){
//事务回滚
//处理异常的代码
}
事情是,你将有重复的代码,不会闻到太好。我建议只要抓住异常,例如:
try {
// PDO code
//事务开始
//如果发生错误(如果出现错误,则抛出手动异常)
抛出新的MyException(all goes tits up);
//交易提交
} catch(异常$ e){
//事务回滚
//处理异常的代码
}
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?
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
}
这篇关于PHP,PDO和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!