为什么Try/Catch在phpredis连接功能中不起作用?

ric*_*hen 7 try-catch redis

我通过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');
Run Code Online (Sandbox Code Playgroud)

但是当redis服务器关闭时,我得到了

    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
Run Code Online (Sandbox Code Playgroud)

catch块没有执行的代码.我回去阅读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');
Run Code Online (Sandbox Code Playgroud)

我可以忍受,但我的好奇心永远不会满足所以我的问题出现了:为什么try/catch方法不能解决连接错误?

Nic*_*lix 4

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