Vikram
Vikram

Reputation: 23

How do I ensure all exceptions in this DB transaction are caught?

I use Yii and recently started using Transactions with try / catch blocks.

Here's how the code looks right now:

    $dbConnection = Yii::app()->db();
    try {
        $transaction = $dbConnection->beginTransaction();
        $dbConnection->createCommand("SELECT * from table_1")
                ->queryAll();

        $transaction->commit();

    } catch (Exception $ex) {
        $transaction->rollback();
    }

Suppose there's an exception with the DB (it's come up while unit-testing), I'm unable to rollback because the PHP dies with a fatal $transaction undefined error.

I'd rather not include isset() checks everywhere.. Is there a simpler way to make this work?

Upvotes: 1

Views: 48

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133370

You can check if the exception is an instance of CDbException

$dbConnection = Yii::app()->db();
try {
    $transaction = $dbConnection->beginTransaction();
    $dbConnection->createCommand("SELECT * from table_1")
            ->queryAll();

    $transaction->commit();

} catch (Exception $ex) {
    if ($ex instanceof CDbException)
    {
      // handle CDBException
      // ...
    }

    $transaction->rollback();
}

Upvotes: 1

Related Questions