PHP,PDO和异常 [英] PHP, PDO, and Exceptions

查看:158
本文介绍了PHP,PDO和异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前对于PDO有一个两难的境地。我最近已经切换到使用自己的自定义数据库类,因为我想利用事务。我正在面临的问题是如何从已经使用try / catch包装的代码块中的PDO中抛出异常。这是一个例子...

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆