我正在尝试对 Redis 和 NodeJS 使用 async/await 关键字。我可以捕获简单的错误,但无法捕获来自 getKeys
函数的异常。以下摩卡测试失败。我的 catch block 也没有被调用。我正在使用 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);
})
})
});
最佳答案
在使用 async/await 时,您应该使用 try/catch block 来处理 Uncaught Error 拒绝。
async getKeys(key) {
let result = await this.client.hgetallAsync(key);
try {
return result;
}
catch (err) {
return err;
}
关于node.js - 在我的异步等待函数中捕获 Uncaught Error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187098/