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?
$redis->connect();
does not throw a an exception if a connection simply fails. What you can do is check if $redis===true, if it is true then you are connected, otherwise you are not connected. But as Nicolas notes below, the exception above is from setex, therefore it will not be catched unless you put it within the try catch block. – Nancienancy