NodeJS Redis (ioredis) hgetall 抛出未定义的错误

NodeJS Redis (ioredis) hgetall throwing undefined error

我正在构建一个使用 ioredis 模块连接到 Redis 集群的 NodeJS 应用程序。

问题概述:

我创建了一个控制器来创建和管理连接:

const redis = require('ioredis');
const consoleLogger = require('../logger/logger.js').console;

const redisCtrl = {};

redisCtrl.defaultPrefix = 'lookup:';

// Local variable to store the full time connection to Redis for lookups
let _redisClient;

// Redis connection config
redisCtrl.redisConnect = {
  port: process.env.REDIS_PORT || 6379,
  host: process.env.REDIS_HOST,
  password: process.env.REDIS_PASSWORD
};

// Redis config
redisCtrl.redisConfig = {
  dnsLookup: (address, callback) => callback(null, address),
  redisOptions: {
    tls: process.env.REDIS_SSL === 'false' ? false : true,
    password: process.env.REDIS_PASSWORD,
    maxRetriesPerRequest: 1
  }
};

// Retrieve the redis connection
redisCtrl.redisClient = async () => {
  if (!_redisClient) {
    _redisClient = await redisCtrl.getNewConnect();
  }
  return _redisClient;
}

redisCtrl.getNewConnect = async () => {
  let makeConnection;

  if (process.env.REDIS_CLUSTER === 'true') {
    makeConnection = new redis.Cluster([redisCtrl.redisConnect], redisCtrl.redisConfig);
  } else {
    makeConnection = new redis(redisCtrl.redisConnect);
  }

  makeConnection.on("connect", function (err) {
    if (!err) {
      consoleLogger.info("REDIS connected");
    } else {
      consoleLogger.info("REDIS connection error");
      consoleLogger.error(JSON.stringify(err));
    }
  });

  makeConnection.on("error", function (error) {
    consoleLogger.info("REDIS error");
    consoleLogger.error(JSON.stringify(error));
    throw new Error(error);
  });

  return makeConnection;
}

redisCtrl.closeInstance = (cb) => {
  if (_redisClient) {
    _redisClient.quit(cb);
  }
}

module.exports = redisCtrl;

这可以建立连接。

但是,当尝试获取结果时,hgetall 方法会抛出一个空错误。

/**
 * Lookup asset by assetId in Redis cache
 * Return asset data object
 * @param {str} assetId
 */
assetsCtrl.lookupByAssetId = async (assetId) => {
  // Prepend default cache prefix to lookup value
  const lookupKey = `${redisPrefix || `lookup:`}${assetId}`;
  let cachedAsset;
  try {
    cachedAsset = await assetsCtrl.redisClient.hgetall(lookupKey);
  } catch (e) {
    consoleLogger.error(`Lookup by assetId failed. Lookup key: ${lookupKey}`);
    consoleLogger.error(e);
    throw new Error(e);
  }
  return cachedAsset;
}

抛出错误但未定义错误。正在调用 redisClient.hgetall(lookupKey) 行的“catch”块,但未定义错误。

error: Lookup by assetId failed. Lookup key: lookup:test123456789
**error: undefined {"command":{"name":"hget","args":["lookup:test123456789"]}}**

问题:如何解决此问题?如何查看所抛出的错误的详细信息?

如上面的评论所述,
hgetall() 不起作用,因为对应于 lookup 值的数据类型不是 hash.

将其更改为 get() 已解决问题。