Home > php, redis > Howto: Handle phpredis connection error

Howto: Handle phpredis connection error

Example Code:

<?php
    $redis=new Redis();
    $connected= $redis->connect('127.0.0.1', 6379);
    if(!$connected) {
        // some other code to handle connection problem
        die( "Cannot connect to redis server.\n" );
    }
    $redis->setex('somekey', 60, 'some value');

I came up with the above code after reading the doc because I found out the following try/catch code doesn’t work as expected

<?php
    $redis=new Redis();
    try {
        $redis->connect('127.0.0.1', 6379);
    } catch (Exception $e) {
    // tried changing to RedisException, didn't work either
        die( "Cannot connect to redis server:".$e->getMessage() );
    }
    $redis->setex('somekey', 60, 'some value');
Advertisements
Categories: php, redis
  1. Philip
    July 20, 2012 at 4:08 am

    You could do a combo of both.

    try {
    $redis = new Redis();
    $connected = $redis->connect(…);
    if (!$connected) { throw new Exception(“Can’t connect”); }
    } catch (Exception $e) {
    die($e->getMessage());
    }

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: