diff --git a/src/InfluxDB/Driver/Curl.php b/src/InfluxDB/Driver/Curl.php index 079efc6..4538e2c 100644 --- a/src/InfluxDB/Driver/Curl.php +++ b/src/InfluxDB/Driver/Curl.php @@ -29,6 +29,9 @@ class Curl implements DriverInterface, QueryDriverInterface /** @var array */ protected $lastRequestInfo; + /** @var mixed */ + protected $lastResponse; + /** * Build the Curl driver from a dsn * Examples: @@ -124,7 +127,13 @@ public function isSuccess() $statusCode = $this->lastRequestInfo['http_code']; if (!in_array($statusCode, [200, 204], true)) { - throw new Exception('Request failed with HTTP Code ' . $statusCode); + $json = json_decode($this->lastResponse); + + if (json_last_error() == JSON_ERROR_NONE && isset($json->error)) { + throw new Exception('Request failed with HTTP Code ' . $statusCode . ': ' . $json->error); + } else { + throw new Exception('Request failed with HTTP Code ' . $statusCode); + } } return true; @@ -152,18 +161,17 @@ protected function execute($url, $curlOptions = []) curl_setopt($ch, CURLOPT_URL, $this->dsn . '/' . $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - $result = curl_exec($ch); + $this->lastResponse = curl_exec($ch); $this->lastRequestInfo = curl_getinfo($ch); - if ($result === false) { + if ($this->lastResponse === false) { // in case of total failure - socket/port is closed etc throw new Exception('Request failed! curl_errno: ' . curl_errno($ch)); } - curl_close($ch); - return $result; + return $this->lastResponse; } /** @@ -203,4 +211,4 @@ public function getDsn() { return $this->dsn; } -} \ No newline at end of file +} diff --git a/tests/unit/Driver/CurlTest.php b/tests/unit/Driver/CurlTest.php index ab11fc0..a567e86 100644 --- a/tests/unit/Driver/CurlTest.php +++ b/tests/unit/Driver/CurlTest.php @@ -217,6 +217,23 @@ public function testIsSuccessThrowsExceptionOnHttpError() $driver->isSuccess(); } + /** + * @expectedException \InfluxDB\Driver\Exception + * @expectedExceptionMessage Request failed with HTTP Code 401: authorization failed + */ + public function testIsSuccessThrowsExceptionWithResponseErrorMessage() + { + $driver = new Curl('http://localhost:8086'); + + static::$MOCK_INFO = ['http_code' => 401]; + static::$MOCK_RESPONSE = '{"error":"authorization failed"}'; + $driver->setParameters(['url' => 'write?something']); + + $driver->write(['data']); + + $driver->isSuccess(); + } + /** * @expectedException \InfluxDB\Driver\Exception * @expectedExceptionMessage Request failed! curl_errno: 999