consul.kv.keys returns always undefined when an error-handling function is passed
FrancescoBorzi opened this issue · 2 comments
Using version 0.31.0
My method:
async keys(path: string): Promise<string[]> {
const data = await this.consul.kv.keys(path);
return data;
}
works fine. However if the path
does not exist, a 500 error will be thrown, crashing the application.
If I pass an error handling function:
async keys(path: string): Promise<string[]> {
const data = await this.consul.kv.keys(path, function(e) {
console.log(e);
});
return data ? data : [];
}
then calling it with a non-existing path
will not make the application crash, because the error will be properly handled. However this will make all calls always returning undefined
(even with existing paths).
You shouldn't mix styles, if you want to use async/await you should use try/catch, if you want to use promises then pass in two functions to then
or call catch
, and if you want to use callbacks then check for error.
Async/await
const consul = require('consul')({ promisify: true });
const mainAsync = async () => {
var results;
try {
var results = await consul.kv.keys('test');
console.log(results);
} catch(error) {
if (error.statusCode === 404) {
console.log('not found');
} else {
console.log(`other error: ${error.statusCode}: ${error.message}`);
}
}
}
mainAsync();
Promise
const consul = require('consul')({ promisify: true });
const mainPromise = () => {
return consul.kv.keys('test').then(
(results) => {
console.log(results);
},
(error) => {
if (error.statusCode === 404) {
console.log('not found');
} else {
console.log(`other error: ${error.statusCode}: ${error.message}`);
}
}
)
}
mainPromise();
Callback
const consul = require('consul')();
const mainCallback = () => {
consul.kv.keys('test', (error, results) => {
if (error) {
if (error.statusCode === 404) {
console.log('not found');
} else {
console.log(`other error: ${error.statusCode}: ${error.message}`);
}
} else {
console.log(results);
}
})
}
mainCallback();
I see, thanks. However it would be nice if the documentation was a bit more detailed about the returned type in order to avoid this kind of confusion.