Skip to content
This repository was archived by the owner on Nov 15, 2022. It is now read-only.

Add error messages returned from InfluxDB to curl driver exceptions #131

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/InfluxDB/Driver/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -203,4 +211,4 @@ public function getDsn()
{
return $this->dsn;
}
}
}
17 changes: 17 additions & 0 deletions tests/unit/Driver/CurlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down