How To Catch Errors When Adding a Field With Knex.JS - javascript

We're using knex.js to generate and execute SQL. We're having trouble trapping errors when adding fields to an existing table and the documentation does not cover this specific use-case. Attempting to add a duplicate field does return an error in the console (VSCODE), but none of standard events are called on an error so we can't trap it in code. Here's the code:
knex.schema.table(tableName, function(table) {
table.string('test').catch(function(e) {
callback(e)
});
}).then(function(e) {
callback(e);
}).catch(function(e) {
callback(e);
})
This is returned in the VSCODE console:
{ [TypeError: table.string(...).catch is not a function] 'error#context': { accessToken: undefined } }
However, none of the callbacks are called. How can we check for errors when adding fields?
UPDATE #1 This code will call the callback, but obviously without any error information. And, the same error appears in the console regardless:
table.string('test').catch(
callback(null, Lib.returnEvent(false))
);
UPDATE #2 No callbacks are called with the following code:
knex.schema.table(tableName, function(table) {
table.string('ddd');
}).then(function(e) {
callback(e);
}).catch(function(e) {
callback(e);
})
UPDATE #3 In this example the first callback is called, but the function hangs on subsequent calls:
knex.schema.table(tableName, function(table) {
table.string('ddd');
callback(true);
}).then(function(e) {
callback(true, e);
}).catch(function(e) {
callback(false, e);
})

I was able to resolve this issue by switching to the Knex callback approach rather than using the promises approach. This code works consistently:
knex.schema.table(tableName, function(table) {
table.string(tableFieldname);
}).asCallback(function(err) {
if (err) {
callback(false, err);
} else {
callback(true);
}
})

This works for me
return knex('users')
.insert({
username: req.body.username,
password: hash,
})
.returning('*')
.bind(console)
.then(console.log)
.catch(console.error);

Related

Not able to catch error for .on() in firebase

I am using below code to retrieve a value
try {
discountFbRef.orderByChild('discode').equalTo(code).on("value", function(snapshot) {
console.log('snapshot val discode', snapshot.val().discode);
if (snapshot.exists()) {
snapshot.forEach(function(data) {
$scope.discountApplicable.id = data.val().id;
});
} else {
console.log('It doesnt exist');
}
}, function(error) {
console.log(error);
});
} catch (error) {
console.log('error occured during search', error);
}
When there is value equal to the search string it's working fine. But when I try to find a keyword that doesn't exist in "discode", It throws
Uncaught TypeError: Cannot read property 'discode' of null
For some reason even though I try to catch the error with try-catch and error function I am not able to catch it.
I need a way to handle the error and show message that search string doesn't exist.
So, the functions that are passed to the second and third parameters of .on are called a callback functions. That means they might get called after (asynchronously) the code you've posted has executed. You'll want to move your try-catch inside of the callback function.
function handleValueSuccess(snapshot) {
try {
console.log('snapshot val discode', snapshot.val().discode);
if (snapshot.exists()) {
snapshot.forEach(function(data) {
$scope.discountApplicable.id = data.val().id;
});
} else {
console.log("It doesn't exist");
}
} catch (error) {
console.log('error occurred during search', error);
}
}
function handleValueError(error) {
console.log('error occurred on value', error);
}
discountFbRef
.orderByChild('discode')
.equalTo(code)
.on("value", handleValueSuccess, handleValueError);

Error : Callback was already called when using pg-promise with async series

I'm having trouble understanding the output printed why executing this code :
1
2
Unhandled rejection Error: Callback was already called.
It seems like both then and catch are executed when the query is successful.
Any idea ?
Cheers
async.series([
function(callback) {
db.none(query)
.then(function () {
return callback(null, true);
})
.catch(function (err) {
return callback(err, null);
});
},
function(callback) {
db.any(query)
.then(function (data) {
console.log('1')
return callback(null, data);
})
.catch(function (err) {
console.log('2')
console.log(err);
return callback(err, null);
});
}
],
function(err, results) {
if (results && !results[1].isEmpty()) {
// do something
}
});
EDIT :
TypeError: results[1].isEmpty is not a function
It seems like the problem come from the rest of the code and was just a simple undefined function error, thanks.
But i still don't understand something : why is this error catched inside the second query instead of outside the async queries ?
I'm the author of pg-promise.
You should never use async library with pg-promise, it goes against the concept of shared/reusable connections.
Implementation with proper use of the same connection, via a task:
db.task(t => {
return t.batch([
t.none(query1),
t.any(query2)
]);
})
.then(data => {
// data[0] = null - result of the first query
// data[1] = [rows...] - result of the second query
callback(null, data); // this will work, but ill-advised
})
.catch(error => {
callback(error, null); // this will work, but ill-advised
});
See also: Chaining Queries.
However, in your case it looks like when you call the successful callback(null, data), it throws an error, which in turn results in it being caught in the following .catch section. To test this, you can change your promise handler like this:
.then(data => {
callback(null, data);
}, error => {
callback(error, null);
});
It should normally throw an error about Promise missing .catch because you threw an error while in .then and there is no corresponding .catch chained below, which you can also check through this code:
.then(data => {
callback(null, data);
}, error => {
callback(error, null);
})
.catch(error => {
// if we are here, it means our callback(null, data) threw an error
});
P.S. You really should learn to use promises properly, and avoid any callbacks altogether. I only provided an example consistent with your own, but in general, converting promises into callbacks is a very bad coding technique.
This is what happens:
callback(null, data) is called within the context of the .then();
async notices that this was the last item of the series, so it calls the final handler (still within the context of the .then());
the final handler throws an error;
because the code runs in the context of .then(), the promise implementation catches the error and calls the .catch();
this calls the callback again;
PoC:
const async = require('async');
async.series([
callback => {
Promise.resolve().then(() => {
callback(null);
}).catch(e => {
callback(e);
});
}
], err => {
throw Error();
})
Have you try to define your function externally:
function onYourFunction() {
console.log('Hi function');
}
and than do:
.then(onYourFunction) //-->(onYourFunction without parentheses )
Unfortunately i don't use pg-promise but i can advise promise
at this point i create all promises that are necessary:
function createPromise(currObj) {
return new Promise(function (resolve, reject) {
currObj.save(function (errSaving, savedObj) {
if(errSaving){
console.log("reject!");
return reject(errSaving, response);
}
console.log('currObj:' + currObj);
return resolve(savedObj);
});
});
}
and then in cascades:
var allPromiseOs = Promise.all(promise1, promise2, promise3);

Trapping AssertionError in nested callback function

I am writing an updated testing library for Node.js and am trying to properly trap errors that occur in test callbacks
for some reason, the following code doesn't trap an AssertionError:
process.on('uncaughtException',function(err){
console.error(err); //an instance of AssertionError will show up here
});
[file1,file2,file2].forEach(function (file) {
self.it('[test] ' + path.basename(file), {
parallel:true
},function testCallback(done) {
var jsonDataForEnrichment = require(file);
request({
url: serverEndpoint,
json: true,
body: jsonDataForEnrichment,
method: 'POST'
}, function (error, response, body) {
if (error) {
done(error);
}
else {
assert(response.statusCode == 201, "Error: Response Code"); //this throws an error, which is OK of course
done();
}
});
});
});
I handle the callback (I named it "testCallback" above), with this code:
try {
if (!inDebugMode) {
var err = new Error('timed out - ' + test.cb);
var timer = setTimeout(function () {
test.timedOut = true;
cb(err);
}, 5000);
}
test.cb.apply({
data: test.data,
desc: test.desc,
testId: test.testId
}, [function (err) { //this anonymous function is passed as the done functon
cb(err);
}]);
}
catch (err) { //assertion error is not caught here
console.log(err.stack);
cb(err);
}
I assume the problem is that callbacks that result from async functions like those made in the request module, cannot be trapped by simple error handling.
What is the best way to trap that error?
Should I just flesh out the process.on('uncaughtException') handler? Or is there a better way?
The best way to handle this appears to be Node.js domains, a core module
https://nodejs.org/api/domain.html
it will likely be deprecated soon, but hopefully there will be a replacement that can have similar functionality, because the domain module is saving my ass right now, as I have no other way to trap errors, because the errors might be generated by my users' code, not my code.

Meteor pattern for multiple method calls sequential callbacks

I keep running into this pattern when coding in Meteor where I find myself making multiple method calls nested within each other - first method fires, then in the callback, a second one fires which is dependent on the first one's result, etc. Is there a better pattern for using multiple methods without nested method calls inside callbacks? The code quickly gets messy.
Meteor.call('unsetProduct', product._id, omitObj, function(err, result) {
if(!err) {
Meteor.call('editProduct', product._id, object, function(err, result) {
if(!err) {
//if no error, then continue to update the product template
Meteor.call('editProductTemplate', self._id, obj, function(err, result) {
if(!err) {
//call some other method
}
else {
FormMessages.throw(err.reason, 'danger');
}
});
}
else {
FormMessages.throw(err.reason, 'danger');
}
});//end edit product
}
else {
AppMessages.throw(err.reason, 'danger');
}
});`
Take a look at reactive-method package. I think it does exactly what you need: it wraps asynchronous Meteor.calls into synchronous code. With it, your code would look cleaner, like
try {
const result = ReactiveMethod.call('unsetProduct', product._id, omitObj);
} catch (error) {
AppMessages.throw(err.reason, 'danger');
}
try {
const nestedResult = ReactiveMethod.call('editProduct', product._id, object);
} catch (error) {
FormMessages.throw(err.reason, 'danger');
}
try {
const evenMoreNestedResult = ReactiveMethod.call('editProductTemplate', self._id, obj);
} catch (error) {
FormMessages.throw(err.reason, 'danger');
}
Which will look nicer when you add some logic inside try statements.

Expects aren't working in Chai as Promised results

I'm new to Promises in JavaScript, and whilst it seems to be working for me to an extent, I'm unable to test the 'reject' value.
I'm passing through an Error, and want to ensure that it is an error and more importantly, that the error code matches what I'm expecting.
return new Promise(function(resolve, reject){
tableService.deleteEntity(config.azureTable.tableName,
visitor.azureEntity(), function (error, response) {
// If successful, go on.
if (!error) {
resolve(response);
}
// If unsuccessful, log error.
else {
/* If we know it's a resourceNotFound
that's causing the error, return that. */
if (error.code === 'ResourceNotFound') {
reject(new Error('Record not found'));
}
// For unexpected errros.
else {
reject(new Error('Table service error (delete): ' + error));
}
}
});
});
The test, in Mocha - using chai and chai-as-promised. Everything else is working (I have 24 passing tests) - but this one has me stuck!
it('return an error when the lookup fails', function (done) {
storage.delete(globalUUID).then(function(sucess) {
done(sucess);
}, function(error) {
expect(error).to.be.an(Error);
done();
});
});
Any help would be greatly appreciated.
You are not using chai-as-promised anywhere. If your first code example is the body of the storage.delete method, then your test should look like:
it('return an error when the lookup fails', function() {
expect(storage.delete(globalUUID)).to.be.rejectedWith(Error);
});

Categories