Get() Function when doc_id not found crashes the code


#1

I want to get the document with specific id, I tried this:

$res = $myBucket->get($document_id);

when a document with document_id exists on the bucket it works fine, but when it’s not found, instead of returning null or something like that, the code crashes and doesn’t continue to run.
I’ve looked at the PHP error log and here is the error:

[15-Dec-2014 14:04:12 America/New_York] PHP Fatal error: Uncaught exception ‘CouchbaseException’ with message ‘The key does not exist on the server’ in CouchbaseNative:1184
Stack trace:
#0 CouchbaseNative(1184): _CouchbaseBucket->get(‘1111’, Array)
#1 /var/www/public/del.php(34): CouchbaseBucket->get(‘1111’)
#2 {main}
thrown in CouchbaseNative on line 1184

What is going wrong?
I’m on Ubuntu 14.04, PHP SDK 2.0.2


#2

Hey hsharghi,

The SDK throws exceptions to indicate error conditions. You should try something like:

try {
  $val = $bucket->get('1111');
} catch(CouchbaseException $e) {
  // Something happened
}

Cheers, Brett


#3

Thanks for quick reply,
Error in PHP error log file is gone, but the code still crashes I think. because if the doc with the id is not found nothing executes anymore

     try {
            $res = $bucket->get($document_id);
        } catch(CouchbaseException $e) {
            // Something happened
            echo ("Error: " + $e);
        }
        echo ("code continues...");

None of the echo commands work when doc is not found.

PS. How did you get your code section highlighted like that?


#4

Hey hsharghi,

Your first echo statement would probably fail due to adding a string to an object. This would yield a value you’re not expecting. Try maybe ("Error:" . $e->toString()). Not sure why your second echo isn’t picking up an error though, it works fine locally.

P.S. To highlight code, it uses GitHub Markdown syntax (ie: opening tag of ```php).

Cheers, Brett


#5

It worked fine. There was a typo in the code.
Everything is working as expected. Thanks man.

PS. for getting the message of the exception.

echo $e->getMessage();