Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Try/Catch doesn't work in phpredis connect function?

I am using redis as a caching store through phpredis. It works perfectly and I want to provide some fail-safe way to make sure the caching feature is always up (using file-based caching, for example), even when redis server goes down, initially I came up with the following code

<?php
    $redis=new Redis();
    try {
        $redis->connect('127.0.0.1', 6379);
    } catch (Exception $e) {
        // tried changing to RedisException, didn't work either
        // insert codes that'll deal with situations when connection to the redis server is not good
        die( "Cannot connect to redis server:".$e->getMessage() );
    }
    $redis->setex('somekey', 60, 'some value');

But when redis server is down, I got

    PHP Fatal error:  Uncaught exception 'RedisException' with message 'Redis server went away' in /var/www/2.php:10
Stack trace:
#0 /var/www/2.php(10): Redis->setex('somekey', 60, 'some value')
#1 {main}
  thrown in /var/www/2.php on line 10

The code the catch block didn't get executed. I went back to read the phpredis doc and came up with the following solution instead

<?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 can live with that but my curiosity would never get satisfied so here comes my question: why the try/catch method doesn't work with the connection error?

like image 960
ricochen Avatar asked Mar 26 '12 23:03

ricochen


2 Answers

Your exception was sent from setex, which is outside of the try {} block. Put the setex inside the try block and the exception will be caught.

like image 93
Nicolas Favre-Felix Avatar answered Nov 21 '22 20:11

Nicolas Favre-Felix


As Nicolas said, the exception comes from setex, but you can avoid that (and even the try/catch block) by using the ping command:

$redis=new Redis();
$redis->connect('127.0.0.1', 6379);

if(!$redis->ping())
{
    die( "Cannot connect to redis server.\n" );
}

$redis->setex('somekey', 60, 'some value');
like image 44
Duru Can Celasun Avatar answered Nov 21 '22 21:11

Duru Can Celasun