How do I handle error in sqlite3? For example, I have this simple code:
var stmt = db.prepare("update Tickets set " + columns + " where id = (?)");
stmt.run(req.body.id);
stmt.finalize();
db.close();
All four functions prepare, run, finalize, close has the potential to throw error. This is on my express.js server so I'm trying to put a res.error() statement somewhere to return result. I don't want to put it in all of them because I can run into a multiple res.setHeader error.
Is there a document on error handling practice with sqlite3? I can't find it in its API documentation.
Take a look at the api. Each of those functions takes a callback, whose first parameter is an error.
This will help you handle an error, but it will not stop your app from crashing. In order to stop a crash, you'll have to use a try/catch , or preferably learn how to use domains.
Errors are emitted on "error" event.
you may want to try doing something like below after you initialise your db handle.
db.on("error", function(error) {
console.log("Getting an error : ", error);
});
Related
I am new to mongoose.I am using Sails js, Mongo DB and Mongoose in my project. My basic requirement was to find details of all the users from my user collection. My code is as follows:
try{
user.find().exec(function(err,userData){
if(err){
//Capture the error in JSON format
}else{
// Return users in JSON format
}
});
}
catch(err){
// Error Handling
}
Here user is a model which contains all the user details. I had sails lifted my app and then I closed my MongoDB connection. I ran the API on DHC and found the following:
When I ran the API for the first time on DHC, the API took more than 30 sec to show me an error that the MongoDB connection is not avaliable.
When I ran the API for the second time, The API timed out without giving an response.
My Question here why is the try and catch block unable to handle such an error exception effectively in mongoose or is it something that I am doing wrong?
EDIT
My Requirement is that mongoose should display the error immediately if the DB connection is not present.
First let’s take a look at a function that uses a synchronous usage pattern.
// Synchronous usage example
var result = syncFn({ num: 1 });
// do the next thing
When the function syncFn is executed the function executes in sequence until the function
returns and you’re free to do the next thing. In reality, synchronous functions should be
wrapped in a try/catch. For example the code above should be written like this:
// Synchronous usage example
var result;
try {
result = syncFn({ num: 1 });
// it worked
// do the next thing
} catch (e) {
// it failed
}
Now let’s take a look at an asynchronous function usage pattern.
// Asynchronous usage example
asyncFn({ num: 1 }, function (err, result) {
if (err) {
// it failed
return;
}
// it worked
// do the next thing
});
When we execute asyncFn we pass it two arguments. The first argument is the criteria to be used by the function. The second argument is a callback that will execute whenever asyncFn calls the callback. asyncFn will insert two arguments in the callback – err and result). We
can use the two arguments to handle errors and do stuff with the result.
The distinction here is that with the asynchronous pattern we do the next thing within the callback of the asynchronous function. And really that’s it.
I'm writing a simple app using Node.js. I use no frameworks (to understand how it works at a "lower" level).
What I'm trying to do:
When a GET request is sent to '/list', I use my MongoDB connection to do a find(). Then I want to iterate over each of the returned items, and display them using response.write("" + myItem).
The problem is that I need to execute a response.end() at the end, and I don't know when "the end" will be -- as all my response.write() statements are executed using callbacks.
Here's my code:
db.items.find({state: "free"}, function(err, myItems) {
if (err) {
console.log("There was an error executing the database query.");
response.end();
return;
}
else if (myItems){
myItems.forEach( function(myItem) {
res.write("<p>" + myItem.title + "</p>\n");
});
}
res.write("</div>");
res.end();
}
I have the feeling I'm missing an idiomatic way to use callbacks here... What's the clean way to fix this?
Thank you!
Thats the correct way, your end() will be called at the end of your callback, so after your foreach loop, the function will go on and send the end() method.
Or maybe did I missed the point of your question. But I think not.
I am using Azure Mobile services-NodeJS backend, and when programming it, I always face this doubt - let me explain using the below code snippet
//--------------------------------------------------------------------------
function addUserToDB(request, response){
///some code here
var theUser = request.user;
///get the user's entity object
try {
objAppUser = buildAppUserEntityObj(theUser, request); //for simplicity sake, lets say this is not asynchronous function
}
catch (err) {
console.log ('error in addUserToDB when calling buildAppUserEntityObj'); //****????****
request.respond(statusCodes.BAD_REQUEST, err);
return; // ##????## is a 'return' needed here to avoid the execution of the code below, or should I assume that the function will return once request is responded (request.respond) in above line.
}
....code to add userEntity to DB
//some more code in case of successful try above, can I assume there is no way this code will be reached in case of error in the above try-catch
// ofcourse I can move this code in the 'try' block above, but I am just trying to understand what happens if above try ends in catch block for some reason and there is no 'return' at the end that catch block.
}
//--------------------------------------------------------------------------
function buildAppUserEntityObj(user, request) {
if ( user.level === 'anonymous' ) { //ideally this would be called in above function, but I am putting this here just to throw an example.
console.error('Anonymous User' );
request.respond(statusCodes.BAD_REQUEST, message); //will this request.respond will send the response to client immediately, or will it be passed on as error the try-catch of above 'addUserToDB' function
return; // ##????## also, is 'return' needed here to avoid the execution of the code below,
}
....code to build a User entity object based on some business logic
}
//--------------------------------------------------------------------------
I guess, it all boils down to three questions:
1. Is 'return' needed in the two places (marked by ##????## in the above two functions?
2. Will the message (marked by //****????**** ) be logged in case user.level === 'anonymous'
3. request.respond vs response.send , whats the difference?
I believe these doubts are because of my lack of thorough expressJS knowledge, so while I am going thru azure/express.js documentation again, I thought I would throw my doubt here to the expert community to get a more clear explanation.
Many thanks.
First
In the second return (insode of buildAppUserEntityObj function, I believe you want it to be:
throw new Error("Anonymous user is not allowed")
Otherwise, even if user is anonymous, your catch code will never execute anyway.
You need the first return;, otherwise it will continue executing the code below.
Second
Message will be logged, if you fix the code described in First paragraph.
Third
There is no request.respond in standard Node.js http module. Can you clarify, what module are you using? That module's API shall answer your question anyway.
QUESTION:
I am writing a node.js code on server which accepts multiple values from client on certain event
var table = data['table'];
var columnName = data['colName']
var columnValue = data['colValue']
var primary_id = data['pid']
var updateQuery = "UPDATE "+table+" SET "+columnName+"=? WHERE primary_id="+primary_id;
var query = conn.query(updateQuery, [columnValue] , function (err, result) {
if (err) throw err;
console.log('changed ' + result.changedRows + ' rows');
});
console.log(query.sql);
// This shows exact query which I wanted to RUN against my MySQL db and also executes successfully on my DB if I try to run this manually.
Problem:
Query formed is correct still that query is not executing through
NODE server.
NODE not showing any error thrown on anonymous call back function and not even result.
NOTE : I have tried to RUN simple select through NODE and that works perfectly [all inclusion are are made correctly for mysql
module and its connection object]
It would be great if some body put some lights on further how to debug this in terms of what kind of error its getting in back-end.
Its was silly mistake ... I was destroying connection each time.
So due to asynchronous nature of JS which indeed used in NODE execution was flowing down with out stopping for query to execute.
..Yes offcourse there is possibly option in NODE to use synchronous nature.
but for now when I removed that line it works like a charm.
//conn.destroy();
I am writing a node js application. I am using request and cheerio to load a set of URLs and get a bunch of information for the site, now let's assume all I am trying to get is the title:
var urls = {"url_1", "url_2", "url_3",...,"url_n"};
for(var i=0; i<urls.length; i++)
{
getDOMTitle(urls[i],function(error,title){
if(error)
console.log("Error while getting title for " + urls[i]);
else
console.log("The title for " + urls[i] + " is " + title);
});
}
This is how my getDOMTitle method looks:
function getDOMTitle(urlReq,callback)
{
var request = require('request');
var cheerio = require('cheerio');
request({url:urlReq},function(error, response, doc){
var $ = cheerio.load(doc);
if(error)
{
callback(true,null);
}
else
{
$('title', 'head').each(function (i, elem) {
var title = $(this).text();
callback(false,title);
});
}
}
}
In the case where the module throws an uncaught exception, how do I handle that situation?
I have tried adding the following:
process.on('uncaughtException', function (err) {
console.error(err);
console.log("Node NOT Exiting...");
callback(true,null);
});
When I do that, I get an error saying I cannot set the headers once they have been sent. If I remove the callback from the process error handling, I do not see that error but the client spins for a long time because I assume we are never calling the callback.
How can I solve this?
Also, I have read somewhere that you can catch uncaught exceptions at the application level so you don't have to replicate the code to catch it in every method, is that possible? and if it is and the method that threw the exception is expected to callback with some information, how can that be achieved?
Thank you,
To answer your stated question, using an uncaught exception handler as a general error-trapping mechanism is commonly regarded as poor design. It's a false economy to use it to handle anything other than non-recoverable situations where you just need to do some cleanup before exiting.
You've got some problems in your example code. In your for loop, all the callbacks are going to report that they were working with the very last URL in your array because they're all referring to the same copy of i, which will be at its highest value by the time any of them execute. You need to use a helper function or an immediate function invocation to give each callback a private copy of i.
In getDOMTitle the error callback should be callback(error) and the code in your loop should include the returned value in the error message. The success callback should use null as its first parameter, though this is just a matter of convention.