Skip to content

Commit d658f52

Browse files
committed
Check we can connect when constructing, throw exception if not
1 parent 7b8f32f commit d658f52

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed

src/PHPCouchDB/Server.php

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ class Server
2424
* @param array $options Supply either a string "url" parameter OR a
2525
* \GuzzleHttp\ClientInterface "client" parameter if more configuration
2626
* is required
27-
* @throws \PHPCouchDB\Exception\ServerException if there's a problem with parsing arguments or creating the client
27+
* @throws \PHPCouchDB\Exception\ServerException if there's a problem
28+
* with parsing arguments or connecting to the database
2829
*/
2930
public function __construct(array $options)
3031
{
@@ -35,20 +36,26 @@ public function __construct(array $options)
3536
}
3637

3738
if (isset($options['client']) && $options['client'] instanceof \GuzzleHttp\ClientInterface) {
38-
$this->client = $options['client'];
39+
$client = $options['client'];
3940
} elseif (isset($options['url'])) {
40-
try {
41-
$this->client = new \GuzzleHttp\Client(["base_uri" => $options['url']]);
42-
} catch (Exception $e) {
43-
throw new \PHPCouchDB\Exception\ServerException(
44-
"Could not connect with URL. Error: " . $e->getMessage()
45-
);
46-
}
41+
$client = new \GuzzleHttp\Client(["base_uri" => $options['url']]);
4742
} else {
4843
throw new \PHPCouchDB\Exception\ServerException(
4944
'Failed to parse $options, array should contain either a url or a client'
5045
);
5146
}
47+
48+
// try to connect as well
49+
try {
50+
$client->get('/');
51+
$this->client = $client;
52+
} catch (\GuzzleHttp\Exception\ConnectException $e) {
53+
throw new \PHPCouchDB\Exception\ServerException(
54+
"Could not connect to database. Error: " . $e->getMessage(),
55+
0, $e
56+
);
57+
}
58+
5259
}
5360

5461
/**

0 commit comments

Comments
 (0)