Skip to content

Commit

Permalink
Better exception handling in mysqli connect
Browse files Browse the repository at this point in the history
  • Loading branch information
develancer committed Apr 29, 2017
1 parent fbed76e commit 663cb65
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
11 changes: 5 additions & 6 deletions lib/Doctrine/DBAL/Driver/Mysqli/MysqliConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,14 @@ public function __construct(array $params, $username, $password, array $driverOp
$this->setDriverOptions($driverOptions);

set_error_handler(function () {});

if ( ! $this->_conn->real_connect($params['host'], $username, $password, $dbname, $port, $socket, $flags)) {
try {
if ( ! $this->_conn->real_connect($params['host'], $username, $password, $dbname, $port, $socket, $flags)) {
throw new MysqliException($this->_conn->connect_error, $this->_conn->sqlstate ?? 'HY000', $this->_conn->connect_errno);
}
} finally {
restore_error_handler();

throw new MysqliException($this->_conn->connect_error, @$this->_conn->sqlstate ?: 'HY000', $this->_conn->connect_errno);
}

restore_error_handler();

if (isset($params['charset'])) {
$this->_conn->set_charset($params['charset']);
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Doctrine/Tests/DBAL/Driver/Mysqli/MysqliConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,33 @@ protected function setUp()
->getMockForAbstractClass();
}

protected function tearDown()
{
if ($this->getName() == "testRestoresErrorHandlerOnException") {
restore_error_handler();
}
}

public function testDoesNotRequireQueryForServerVersion()
{
$this->assertFalse($this->connectionMock->requiresQueryForServerVersion());
}

public function testRestoresErrorHandlerOnException()
{
$handler = function () { self::fail('Never expected this to be called'); };
$default_handler = set_error_handler($handler);

try {
new MysqliConnection(['host' => '255.255.255.255'], 'user', 'pass');
self::fail('An exception was supposed to be raised');
} catch (MysqliException $e) {
self::assertSame('Network is unreachable', $e->getMessage());
}

self::assertSame($handler, set_error_handler($default_handler), 'Restoring error handler failed.');
}

/**
* @dataProvider secureMissingParamsProvider
*/
Expand Down

0 comments on commit 663cb65

Please sign in to comment.