Skip to content

Responses and Errors

Daniel Carbone edited this page Nov 6, 2026 · 1 revision

Responses and Errors

Response objects

Every client method returns a response object. It can be used in two ways:

  1. Destructured, like the multiple return values of the Go client:

    [$pair, $qm, $err] = $consul->KV->Get(key: 'app/config/db');
  2. 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.

Shapes

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).

Value types

  • A missing item is not an error for some single-item reads. KV->Get of a missing key returns [null, $qm, null], and so do Catalog->Node and 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 array of models (empty when Consul returns null), 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 in foreach and count() like arrays.
  • Map endpoints (e.g. Catalog->Services, Agent->Services) return an associative array.

Transactions

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.

QueryMeta

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

WriteMeta

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)

Errors

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'));

Exceptions that are thrown

Programming errors are thrown as normal PHP exceptions, not returned:

  • \InvalidArgumentException for invalid constructor or setter input, such as a negative or non-numeric big integer, an invalid duration string, a CertFile without a KeyFile, or an unknown kind passed to Consul::MakeConfigEntry().
  • \RuntimeException when TokenFile cannot be read.
  • \TypeError when an argument has the wrong PHP type.

Clone this wiki locally