我正在尝试使用Redis和NodeJS的async / await关键字。我可以捕获简单的错误,但我无法捕获来自getKeys
函数的异常。以下摩卡测试失败。我的catch块也没有被调用。我使用的是NodeJS v9.3.0和bluebird v3.5.1以及redis 2.8.0
const redis = require("redis");
const bluebird = require("bluebird");
const assert = require('assert');
bluebird.promisifyAll(redis.RedisClient.prototype);
class RedisManager {
constructor(host) {
this.client = redis.createClient({'host':host});
}
async getKeys(key) {
let result = await this.client.hgetallAsync(key);
return result;
}
async simple(key) {
throw Error('Simple Error: ' + key)
}
}
describe('Redis Manager Test:', function() {
it('catches simple errors',function (done) {
let manager = new RedisManager('BOGUSHOST');
let key = 'testKey';
manager.simple(key)
.then(function (value) {
console.log('Value: ' + value);
done(value,null)
})
.catch(function (err) {
if (err = Error('Simple Error: ' + key)) {
done(null);
} else {
done(err);
}
})
});
it('catches Redis errors',function(done) {
let manager = new RedisManager('BOGUSHOST');
manager.getKeys('Some')
.then(function(value) {
console.log('Value: ' + value);
done(value,null)
})
.catch(function (err) {
console.log('Caught Error: ' + err);
done(err,null);
})
})
});
答案 0 :(得分:0)
使用async / await时,您应该使用try / catch块来处理未捕获的错误拒绝。
async getKeys(key) {
let result = await this.client.hgetallAsync(key);
try {
return result;
}
catch (err) {
return err;
}
}