V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
raysonlu
V2EX  ›  PHP

PHP 如何连接 redis 失败后不报错跳过继续执行代码?

  •  
  •   raysonlu · 2018-07-25 11:37:03 +08:00 · 4789 次点击
    这是一个创建于 2074 天前的主题,其中的信息可能已经有所发展或是发生改变。

    项目某部分缓存想使用 redis 部署,默认是使用文件缓存的,但不确保 redis 服务是否正常连接,希望检测到 redis 连接不成功则自动切换到文件缓存,有什么方法?

    php 去连接 redis 服务器,发现连接不成功就直接给出致命错误中止代码运行了,try{}cahtch()无法捕捉致命错误

    10 条回复    2018-08-24 09:45:54 +08:00
    update
        1
    update  
       2018-07-25 13:00:02 +08:00
    使用的什么 redis 类库? 看是不是类库里面直接报错了。
    sorshion
        2
    sorshion  
       2018-07-25 13:06:34 +08:00
    php7 试试 try{}catch(\Error $e){}
    sparrww
        3
    sparrww  
       2018-07-25 13:44:20 +08:00
    为什么捕捉不到,尝试了吗
    vus520
        4
    vus520  
       2018-07-25 13:57:17 +08:00
    原生的 Redis 类,所有异常都是可以捕获的。
    DavidNineRoc
        5
    DavidNineRoc  
       2018-07-25 14:06:35 +08:00
    不上截图一律按照自己的代码问题处理,
    如果用 predis,有连接失败的异常 https://github.com/phpredis/phpredis/#class-redisexception
    > phpredis throws a RedisException object if it can't reach the Redis server. That can happen in case of connectivity issues, if the Redis service is down, or if the redis host is overloaded. In any other problematic case that does not involve an unreachable server (such as a key not existing, an invalid command, etc), phpredis will return FALSE.
    caola
        6
    caola  
       2018-07-25 14:10:33 +08:00
    php7 试试 try{}catch(\Error $e){}  +1
    dobelee
        7
    dobelee  
       2018-07-25 14:17:46 +08:00
    set_error_handler()

    try {}
    catch(\ErrorException $e) {}
    catch(\Exception $e) {}

    了解一下,捕捉一切异常。
    spkinger
        8
    spkinger  
       2018-07-25 14:23:12 +08:00
    还有一个 Throwable,
    这个也可以尝试 catch 下
    raysonlu
        9
    raysonlu  
    OP
       2018-07-25 14:46:39 +08:00
    哈哈,小弟问题,确实能捕捉了!原来是框架问题,没有在初始化的时候连接 redis,所以我在那儿 try catch 总是没有反应,哈哈。谢谢各位大神了!
    ksharp8
        10
    ksharp8  
       2018-08-24 09:45:54 +08:00
    行前加 @或者首行加 error 类代码,或者 php.ini 调整报错等级
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2941 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 78ms · UTC 11:07 · PVG 19:07 · LAX 04:07 · JFK 07:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.