What is the syntax preferred while using PDO transaction and try catch and Why?
$dbh->beginTransaction();
try {
} catch (Exception $e) {
}
OR
try {
$dbh->beginTransaction();
} catch (Exception $e) {
}
The existent answers seem to suggest that since $dbh->beginTransaction() could throw a PDOException it should be in the same try block of the actual transaction code, but this means that the rollBack() code itself will be wrong, because it could invoke a rollBack() without there being a transaction, which could also throw another PDOException.
The right logical ordering of this is that you put the code you want executed in one transaction in one catch block after the transaction has been created. You could also check that the return of beginTransaction() is true before proceeding. You could even check that the database session is in a transaction before calling rollback().
if ($dbh->beginTransaction())
{
try
{
//your db code
$dbh->commit();
}
catch (Exception $ex)
{
if ($dbh->inTransaction())
{
$dbh->rollBack();
}
}
}
Keep in mind that you could still, at least in theory, get an exception from beginTransaction() and rollBack() so I would put this in a separate function and enclose the invocation in another try-catch block.
You could also bubble the exception you get up to catch it and log all Exceptions in one place. But remember that some exceptions could be data integrity errors such as duplicate keys or invalid foreign keys, which would not be a database fault as such, but most probably a bug in your code.
With this approach, the main thing to keep in mind here is that the two try-catch blocks have a slightly different purpose. The inner one is purely to ensure that multiple queries are executed and committed atomically in one transaction and if something happens they are rolled back. The external try-catch would be to detect erroneous situations and log it, or whatever you would want to do if you have a problem with your database.
try {
$dbh->beginTransaction();
} catch (Exception $e) {
}
Simply because an exception could be thrown as you attempt to begin the transaction.
Note that you can place another try catch block inside the initial try.
The second one usually makes most sense. Since you may not always know what will cause the transaction to fail, you would want the rollback (and possibly commit) logic available in the catch, so you'd want to put the beginTransaction() inside of the try.
In addition to the try/catch make sure you set the error mode attribute:
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
And if anything you should catch the PDOExecption just because you should not treat all exception in the same way.
try {
$dbh->beginTransaction();
//do stuff
$dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
//...
throw $e;
}
But if you still want to catch other exception add more catch blocks:
try {
....
} catch (PDOException $e) {
//handle pdo exception
}catch (Exception $ex) {
//handle others differently
}
Related
try {
} catch (Exception $e) {
}
I thought PHP had type inference. Why is it neccesary to declare the type of the variable --$e-- ?
The code can throw different classes of exceptions. You can use that to your advantage to add proper code for error handling.
A try block can be followed by any number of catch blocks.
Example:
try
{
}
catch(\PDOException $e)
{
// Something bad happened while dealing with database
}
catch(\LengthException $e)
{
// Length exception occurred
}
catch(\Exception $e)
{
// The \Exception is the parent class for all exceptions, this handles anything not caught in above example
}
Using the above sample, you can take proper measures for handling errors depending on why they occurred. That means you can throw exceptions that you defined. It's the best if you don't overdo it and swap out entire error handling with exceptions. Exceptions occur when something abnormal in the code flow occurs, for example - a connection to MySQL broke mid-transaction.
Will this work? I'd test it but I don't know how to crash things half way though.
$db = DB::getDB();
try{
$db->begintransaction();
Invoice::saveInvoice($info, $db);
InvoiceDetails::saveDetails($moreInfo, $db);
$db->commit();
}catch(Exception $e){
$db->rollback();
}
And if it does work is there anything that could bite me in the butt besides doing something that causes a implicit commit?
The only thing I'd do is fix up your exception handling. For example
catch (Exception $e) {
$db->rollback();
throw $e;
}
Doing this lets you safely rollback the transaction as well as letting the error bubble up further in your application.
You could even wrap the inner exception (which will probably be a PDOException) with one of your choosing, eg
$db->rollback();
throw new RuntimeException('Error saving invoice details', 0, $e);
To "crash things half way though", simply throw an exception within one of your save* methods, eg
throw new Exception('KA-BLAM!');
After looking into using try catch blocks for my Pdo statements is it really a benefit? Does this just slow your code down?
I believe that there should be a try catch around the connection command in case the database connection fails. But does there really need to be try catch around each pre prepared statement? These should never change and never really error out.
Any thoughts?
I'm using Php and MySql.
There is no benefit to this:
try {
// exec statement
// exec statement
}
catch (Exception $e) {
// do nothing
}
If you aren't going to do anything with the error and provide a reasonable solution, then you may as well let the exception bubble up to the application's main "something went wrong" error page.
But you may want to do this:
// begin transaction
try {
// exec statement
// exec statement
// commit transaction
}
catch (Exception $e) {
// rollback transaction
// handle error or rethrow $e;
}
And prepared statements can throw exceptions. Perhaps a unique key is violated, or a foreign key constraint is, etc.
But the main point is, you don't use exceptions to hide or silence errors. You use them to catch an error, process it intelligently, and continue on accordingly.
Should I do
$dbh->beginTransaction();
try{
Or
try{
$dbh->beginTransaction();
It doesn't really matter, it will run the code indifferent of it's position.
But you want to put the rollback() in the catch, and with that setup it's not readable if you put begin outside.
I would vote for inside the try.
It probably doesn't really matter. However, it's better to place the beginTransaction outside the try. When the beginTransaction fails, it should not execute the rollback.
add it inside the try/catch block, so you can catch any PDOException:
try {
$dbh->beginTransaction(); // start transaction
$stmt = $dbh->query($query); // run your query
$dbh->commit(); // commit
} catch(PDOException $ex) { // if exception, catch it
$dbh->rollBack(); // rollback query
echo $ex->getMessage(); // echo exception message
}
In this case it doesn't matter, as beginTransaction will return false on failure. If it threw exceptions, you would want it inside of a nested try block (otherwise you'd execute rollBack() after catching the exception which would fail because no transaction was started).
If you want to catch the possible errors that the beginTranscation method should throw, go for the second one.
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
}
try{
//code here
}
catch(PDOException $e){
//handle PDO
throw $e; //to rethrow it upper if need
}
catch(Exception $e){
//handle any other
}
If something is going wrong PDO will generate exception. But if you make some changes in db and would like to revert all you can run
throw new PDOException(....);