Here is my basic php code:
try{
$db = new PDO("mysql:dbname=name;host=localhost", $db_username, $db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//run queries etc...
} catch (PDOException $e) {
//handle and log error appropriately
}
Is there an easy way to reach the catch block or force a PDOException so that I can test and/or debug the page in the event that a database error occurs?
Is there an easy way to reach the catch block
Yes. Like in any other case, just force an intentional error.
or force a PDOException
Just like any other exception, throw new PDOException('test');
} catch (PDOException $e) {
//handle and log error appropriately
}
This is wrong way of handling errors. Create and install an exception handler. While you have to keep try..catch for another purpose.
Make a fake (bad) connection. If your db name is 'name', put 'name1'.
-EDIT- What's with the downvote? It works... Would've commented, but I can't yet.
Related
i try to implement a fallback solution for when my database is not available. Somhow i do not manage to catch the error.
Call to create connection:
if(!$this->connection = mysqli_connect(
$this->host,
$this->name,
$this->pass,
$this->db
)) { throw new Exception('Unable to connect to Database'); }
init.php to include dbClass
require_once __DIR__ . '/../classes/Database.php';
$db = new Database();
$connection = $db->getConnection();
actual usage with try catch wrap
try {
include __DIR__ . '/../out/script/content/config/init_direct.php';
... do stuff regulary
}catch (Exception $e) {
... do fallback stuff
}
i do not get into the catch block. for test purpose i just set the database offline.
there are several problems with your approach
First, your problem is insufficient debugging. You just assume that exception has been thrown, but in reality it weren't.
Second, this happened because mysqli_connect returns an object, not boolean you expect.
Third, as you've been told in the comments, errors aren't exceptions and you cannot catch them.
Anyway, with mysqli you don't need to throw exceptions manually - this extension can throw them by itself, so, all you need is to set the proper mode up - an exception will be thrown which will be caught all right.
I need to redirect to a separate page to show error. header("Location: errorpage.php?errorcode=11"); after does not seem to work.
<?php
$db = new PDO("mysql:host=localhost;dbname=mydbase;charset=utf8", "user", "password");
try {
$db->beginTransaction();
$db->exec("SOME QUERY");
$db->commit();
}
catch(PDOException $ex) {
$db->rollBack();
//Something went wrong so I need to redirect
header("Location: errorpage.php?errorcode=11");
}
PDO's error handling is a little unusual. It has modes for throwing real exceptions, issuing PHP warnings, or just being silent.
Silent is the default. What has happened here is that no exception is ever thrown because you did not configure PDO to throw one. So the catch block is never entered and header() is never called. Setup your $db object to throw exceptions:
// Ensure PHP's native error handling is showing
// on screen (to catch problems with header() itself)
error_reporting(E_ALL);
// Always in development, disabled in production
ini_set('display_errors', 1);
$db = new PDO("mysql:host=localhost;dbname=mydbase;charset=utf8", "user", "password");
// Turn on exceptions for PDO so the try/catch is meaningful
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$db->beginTransaction();
$db->exec("SOME QUERY");
$db->commit();
}
catch(PDOException $ex) {
$db->rollBack();
//Something went wrong so I need to redirect
header("Location: errorpage.php?errorcode=11");
// Always make an explicit call to exit() after a redirection header.
exit();
}
About PDO::exec():
I know this is example code, but exec() is not usually the right method to use. If you are doing DDL statements, the transaction won't work since MySQL doesn't support that, and if you are doing things like INSERT/UPDATE/DELETE with any user input, you should be doing prepare()/execute() to create an injection-safe prepared statement instead.
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
}
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!');
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(....);