A newer version of this documentation is available.

View Latest

Handling Errors

Practical steps to handle errors and exceptions.

Errors are inevitable. The developer’s job is to be prepared for whatever is likely to come up — and to try and be prepared for anything that conceivably could come up. Couchbase gives you a lot of flexibility, but it is recommended that you equip yourself with an understanding of the possibilities.

As covered here, the PHP SDK ships with two different APIs, allowing you to structure your application the way you want. That guide also covers how errors are actually returned and handled.

Exception Handling

SDK 3.x actively uses Exceptions to signal errors. Instead of using single \Couchbase\Exception, as in SDK 2.x, now we use a hierarchy of exceptions, which allows the handling of errors in a more reliable way:

try {
    $collection->get("foo");
} catch (\Couchbase\KeyNotFoundException $ex) {
    printf("Document does not exist, creating");
    $collection->upsert("foo", ["bar" => 42]);
}

Instead of SDK 2.x’s:

try {
  $bucket->get("foo");
} catch (\Couchbase\Exception $ex) {
  if ($ex->getCode() == COUCHBASE_KEYNOTFOUND) {
    $bucket->upsert("foo", ["bar" => 42]);
  }
}