为什么Try/Catch不';在phpredis连接功能中不工作?

为什么Try/Catch不';在phpredis连接功能中不工作?,redis,try-catch,Redis,Try Catch,我通过phpredis使用redis作为缓存存储。它工作得非常完美,我想提供一些故障安全的方法来确保缓存功能始终处于启动状态(例如,使用基于文件的缓存),即使redis服务器停机,最初我还是会想到以下代码 <?php $redis=new Redis(); try { $redis->connect('127.0.0.1', 6379); } catch (Exception $e) { // tried changing to

我通过phpredis使用redis作为缓存存储。它工作得非常完美,我想提供一些故障安全的方法来确保缓存功能始终处于启动状态(例如,使用基于文件的缓存),即使redis服务器停机,最初我还是会想到以下代码

<?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');
捕获块中的代码没有执行。我回去阅读了phpredis文档,并提出了以下解决方案

<?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');

您的异常是从setex发送的,它在try{}块之外。将setex放入try块中,将捕获异常。

正如Nicolas所说,异常来自setex,但您可以通过使用
ping
命令避免该异常(甚至是try/catch块):

$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');

如果捕获“\Predis\connection\ConnectionException”,它将能够捕获连接异常


或者可以使用\Exception代替Exception(注意前面的正斜杠)

我想他会发现一个关于服务不可用的异常,以及一个错误命令的异常。@Niloct,你读到了我的想法:D如果在调用connect()时能发现异常确实很好。谢谢你的回答,但我不明白为什么要使用额外的命令(回答中的ping)比只检查connect()的结果要好,这正是我在代码中实际使用的结果。
$redis->connect()不会引发异常。您可以做的是检查$redis===true,如果为true,则您已连接,否则您未连接。但是正如Nicolas在下面所指出的,上面的异常来自setex,因此除非您将它放在try-catch块中,否则它不会被捕获。@haluk Redis-connect方法抛出异常。这是不正确的。您提到的异常,
\Predis\Connection\ConnectionException
,是由而不是由引发的。
$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');