Neil Harlow
Neil Harlow

Reputation: 110

How to force PDOException / reach catch block (php)

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?

Upvotes: 0

Views: 1498

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157892

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.

Upvotes: 2

wiscWeb
wiscWeb

Reputation: 213

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.

Upvotes: 1

Related Questions