josepmra
josepmra

Reputation: 627

zend framework 2 no catch PDO exceptions using Db Adapter

I am using the Zend\Db\Adapter\Adapter to launch queries with PDO_Mysql driver. I want to catch the primary key violation with PDOException class.

The following code catches correctly the exception and shows the first message. It's based on a query method with execute mode.

    try {
        $dbAdapter = new DbAdapter(array(
                'driver' => 'Pdo_Mysql', 'database' => 'securedraw',
                'username' => 'root', 'password' => '',));          

        $sql = "INSERT INTO users (mail, password) values('josep', 'josep')";
        $dbAdapter->query($sql, DbAdapter::QUERY_MODE_EXECUTE);

    }catch (\PDOException $e) {
        print "First Message " . $e->getMessage() . "<br/>";
    }catch (\Exception $e) {
        print "Second Message: " . $e->getMessage() . "<br/>";
    }

I don't understand because this code doesn't catch it (the unique change is that it's a prepared statement).

In this case show the second message which is much more generic and doesn't said if the error is primary key violation.

    try {
        $dbAdapter = new DbAdapter(array(
                'driver' => 'Pdo_Mysql', 'database' => 'securedraw',
                'username' => 'root', 'password' => '',));          

        $sql = "INSERT INTO users (mail, password) values('josep', 'affsafq')";
        $statement = $dbAdapter->createStatement($sql);
        $statement->execute();  

    }catch (\PDOException $e) {
        print "First Message "   . $e->getMessage() . "<br/>";
    }catch (\Exception $e) {
        print "Second Message: " . $e->getMessage() . "<br/>";
    }

Upvotes: 0

Views: 2934

Answers (1)

Xerkus
Xerkus

Reputation: 2705

You should check exceptions in php manual

}catch (\Zend\Db\Adapter\ExceptionInterface $e) {
    $message = $e->getPrevious() ? $e->getPrevious()->getMessage() : $e->getMessage();
    print "First Message "   . $message . "<br/>";
}catch (\Exception $e) {
    print "Second Message: " . $e->getMessage() . "<br/>";
}

Upvotes: 2

Related Questions