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

2018-07-25 11:37:03 +08:00
 raysonlu

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

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

4831 次点击
所在节点    PHP
10 条回复
update
2018-07-25 13:00:02 +08:00
使用的什么 redis 类库? 看是不是类库里面直接报错了。
sorshion
2018-07-25 13:06:34 +08:00
php7 试试 try{}catch(\Error $e){}
sparrww
2018-07-25 13:44:20 +08:00
为什么捕捉不到,尝试了吗
vus520
2018-07-25 13:57:17 +08:00
原生的 Redis 类,所有异常都是可以捕获的。
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
2018-07-25 14:10:33 +08:00
php7 试试 try{}catch(\Error $e){}  +1
dobelee
2018-07-25 14:17:46 +08:00
set_error_handler()

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

了解一下,捕捉一切异常。
spkinger
2018-07-25 14:23:12 +08:00
还有一个 Throwable,
这个也可以尝试 catch 下
raysonlu
2018-07-25 14:46:39 +08:00
哈哈,小弟问题,确实能捕捉了!原来是框架问题,没有在初始化的时候连接 redis,所以我在那儿 try catch 总是没有反应,哈哈。谢谢各位大神了!
ksharp8
2018-08-24 09:45:54 +08:00
行前加 @或者首行加 error 类代码,或者 php.ini 调整报错等级

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/473966

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX