Repository navigation
Responses and Errors
Every client method returns a response object. It can be used in two ways:
-
Destructured, like the multiple return values of the Go client:
[$pair, $qm, $err] = $consul->KV->Get(key: 'app/config/db');
-
As an object, through public properties or getters:
$resp = $consul->KV->Get(key: 'app/config/db'); $resp->Value; $resp->getValue(); $resp->QueryMeta; $resp->getQueryMeta(); $resp->Err; $resp->getErr();
Responses implement \ArrayAccess for destructuring only. They are read-only: $resp[0] = ... and unset($resp[0])
throw \BadMethodCallException, and reading an offset outside the shape throws \OutOfRangeException.
| Kind | Destructure | Properties | Example |
|---|---|---|---|
| Query with value | [$value, $qm, $err] |
Value, QueryMeta, Err
|
KV->Get, Catalog->Services
|
| Write with value | [$value, $wm, $err] |
Value, WriteMeta, Err
|
Session->Create, KV->CAS
|
| Write without value | [$wm, $err] |
WriteMeta, Err
|
KV->Put, KV->Delete
|
| Value only | [$value, $err] |
Value, Err
|
Status->Leader, Agent->Self
|
| Error only | n/a (returns null|Error) |
Agent->ServiceRegister, Agent->PassTTL
|
|
| Agent health | [$status, $info, $err] |
Agent->AgentHealthServiceByID |
|
| Transaction | not destructurable |
OK, *TxnResponse, QueryMeta, Err
|
KV->Txn, Txn->Txn
|
The exact shape of every method is listed on its client page (e.g. KV, Agent).
- A missing item is not an error for some single-item reads.
KV->Getof a missing key returns[null, $qm, null], and so doCatalog->Nodeand similar reads. Others return an error with the 404/403 body, matching the Go client (e.g.ConfigEntry->Get,ACL->TokenRead). - List endpoints return a PHP
arrayof models (empty when Consul returnsnull), or one of a few collection classes that implement\IteratorAggregate,\Countable, and\ArrayAccess:KV\KVPairs,Health\HealthChecks,Agent\AgentServiceChecks,Txn\TxnResults. These can be used inforeachandcount()like arrays. - Map endpoints (e.g.
Catalog->Services,Agent->Services) return an associativearray.
KV->Txn and Txn->Txn return a response with an OK flag, because a transaction can be rolled back without the
request failing:
$resp = $consul->Txn->Txn(null, ...$ops);
if (null !== $resp->Err) {
// transport / unexpected status error
} elseif (!$resp->OK) {
foreach ($resp->TxnResponse->Errors as $txnErr) {
echo "op {$txnErr->OpIndex}: {$txnErr->What}\n";
}
} else {
foreach ($resp->TxnResponse->Results as $result) { /* ... */ }
}See Txn.
Returned by read endpoints. Built from the X-Consul-* response headers.
| Property | Type | Description |
|---|---|---|
RequestUrl |
string |
Full URL that was requested |
LastIndex |
BigInteger |
X-Consul-Index; pass as WaitIndex for blocking queries |
LastContentHash |
string |
X-Consul-ContentHash; pass as WaitHash for hash-based blocking |
LastContact |
int |
Milliseconds since the server last contacted the leader |
KnownLeader |
bool |
Whether the server knows of a leader |
RequestTime |
Time\Duration |
Round-trip time of the request |
AddressTranslationEnabled |
bool |
X-Consul-Translate-Addresses |
CacheHit |
bool |
Whether the result came from the agent cache |
CacheAge |
Time\Duration |
Age of the cached result |
Returned by write endpoints.
| Property | Type | Description |
|---|---|---|
RequestTime |
Time\Duration |
Round-trip time of the request |
Warnings |
string[] |
Warnings reported by Consul (e.g. X-Consul-KV-Warning) |
Transport failures, unexpected HTTP status codes, and JSON decode failures are returned, never thrown, as
DCarbone\PHPConsulAPI\PHPLib\Error:
[$pair, $qm, $err] = $consul->KV->Get(key: 'app/config/db');
if (null !== $err) {
$logger->error((string)$err);
return;
}| Method | Returns | Description |
|---|---|---|
getMessage() |
string |
Error message |
getTime() |
Time\Time |
When the error was created |
__toString() |
string |
Same as getMessage()
|
jsonSerialize() |
\stdClass |
{"message": ..., "timestamp": ...} |
Typical messages:
DCarbone\PHPConsulAPI\KV\KVClient - Error seen while executing "http://127.0.0.1:1/v1/kv/x". Message: "cURL error 7: ..."
DCarbone\PHPConsulAPI\KV\KVClient - Unexpected response code seen. Expected: [200]; Response code: 403; Response: ACL not found
The response body is included in the message, so a 403 from an ACL check can be diagnosed from the string.
If you prefer exceptions, wrap the call:
use DCarbone\PHPConsulAPI\PHPLib\AbstractResponse;
function must(AbstractResponse $resp): mixed
{
if (null !== $resp->Err) {
throw new \RuntimeException((string)$resp->Err);
}
return $resp->Value ?? null;
}
$pair = must($consul->KV->Get(key: 'app/config/db'));Programming errors are thrown as normal PHP exceptions, not returned:
-
\InvalidArgumentExceptionfor invalid constructor or setter input, such as a negative or non-numeric big integer, an invalid duration string, aCertFilewithout aKeyFile, or an unknown kind passed toConsul::MakeConfigEntry(). -
\RuntimeExceptionwhenTokenFilecannot be read. -
\TypeErrorwhen an argument has the wrong PHP type.