NodeJS 未处理的错误事件:错误:connect ECONFREFUSED-无法正常处理此错误

1tu0hz3e  于 2023-02-15  发布在  Node.js
关注(0)|答案(2)|浏览(193)

我正在寻找一个解决方案,在那里我可以优雅地处理redis连接问题。假设我的redis服务关闭,什么将是最好的方式来处理错误。我试图把我的代码在try catch,但不幸的是redis是不抛出异常,无法捕捉我的nodejs代码中的异常。我尝试了包中的各种设置,如ioredis(即maxRetriesPerRequest:0)或node-redis但失败了。你能给我一些参考或帮助来优雅地处理连接问题吗?

m0rkklqb

m0rkklqb1#

try {
    const client = createClient({
        url: 'redis://redis.xyz.com>:6379'
    });
    client.on('error', (err) => console.log('Redis Client Error', err));
    await client.connect();
    await client.set('key', 'value');
    const value = await client.get('key');
    console.log("Value", value);
}
catch (err: any) {
     //Unable to reach here. Redis is not throwing error on redis connection issue
    //Want to call api to fetch info when server is down
}
    
In this, I want to gracefully handle connection timeout if redis connection fails and want that if connection fails than I want to fetch the info from the api in place of redis keep trying to connect to redis server if connection fails.In current settings, if connection fails, system keep trying to connnect to redis server and somewhat blocks the event loop in nodejs.Please suggest how can we avoid this.

相关问题