azure node.js request, response - seeking some clarification - node.js

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.

Related

Updating a user concurrently in mongoose using model.save() throws error

I am getting a mongoose error when I attempt to update a user field multiple times.
What I want to achieve is to update that user based on some conditions after making an API call to an external resource.
From what I observe, I am hitting both conditions at the same time in the processUser() function
hence, user.save() is getting called almost concurrently and mongoose is not happy about that throwing me this error:
MongooseError [ParallelSaveError]: Can't save() the same doc multiple times in parallel. Document: 5ea1c634c5d4455d76fa4996
I know am guilty and my code is the culprit here because I am a novice. But is there any way I can achieve my desired result without hitting this error? Thanks.
function getLikes(){
var users = [user1, user2, ...userN]
users.forEach((user) => {
processUser(user)
})
}
async function processUser(user){
var result = await makeAPICall(user.url)
// I want to update the user based on the returned value from this call
// I am updating the user using `mongoose save()`
if (result === someCondition) {
user.meta.likes += 1
user.markModified("meta.likes")
try {
await user.save()
return
} catch (error) {
console.log(error)
return
}
} else {
user.meta.likes -= 1
user.markModified("meta.likes")
try {
await user.save()
return
} catch (error) {
console.log(error)
return
}
}
}
setInterval(getLikes, 2000)
There are some issues that need to be addressed in your code.
1) processUser is an asynchronous function. Array.prototype.forEach doesn't respect asynchronous functions as documented here on MDN.
2) setInterval doesn't respect the return value of your function as documented here on MDN, therefore passing a function that returns a promise (async/await) will not behave as intended.
3) setInterval shouldn't be used with functions that could potentially take longer to run than your interval as documented here on MDN in the Usage Section near the bottom of the page.
Hitting an external api for every user every 2 seconds and reacting to the result is going to be problematic under the best of circumstances. I would start by asking myself if this is absolutely the only way to achieve my overall goal.
If it is the only way, you'll probably want to implement your solution using the recursive setTimeout() mentioned at the link in #2 above, or perhaps using an async version of setInterval() there's one on npm here

Wrapping/intercepting a promise in an inner function

I'm having difficulty finding an answer to my question, perhaps because I don't know how to ask it (what search terms to use). I'm really struggling to understand promises, and have watched a number of tutorial videos and am still not getting some fundamental piece to make it click.
In Node, I am using the request-promise module, which returns a promise when I make a call to an rp() method. I am calling
return rp(service);
from within a function. But what I want to do, instead, is add a .then() handler to this to do some post-processing with the result of the service call, BEFORE returning the promise back to the caller so the caller can still have its own then handler.
How do I accomplish this?
It would be helpful to see your current code to better understand where exactly you are struggling with.
In general, you can think of promises as a placeholder for some future value that you can chain together.
If I understood your question correctly, you would like to make a request to a server, receive the response, do something with the response and return it back to the caller.
const callService = (url) => {
// make sure to return your promise here
return rp(url)
.then((html) => {
// do something with html
return html;
});
};
Now you can call it like so -
callService('http://www.google.com')
.then((html) => {
console.log(html);
}).catch((err) => {
// error handling
});
The common mistake is to omit the return statement in your top level function and subsequent then functions.
Feel free to provide additional details.

Unable to understand why the try and catch is not working as expected in mongoose

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.

What's a simple way to log a programming error in node?

NOTE: I edited this question to more accurately show the problem, rather than delete and rewrite it. Hope that's OK.
For the following code:
var Q = require('q');
function first (){
var d = Q.defer();
setTimeout(function(){
d.resolve([]);
}, 1000);
return d.promise;
}
function second(v){
sdf;
console.log("hi")
}
first()
.then(second);
How can I determine that there is a ReferenceError in there? Is the only option to add a second function argument in the then call?
Even though it's not recommended, I tried using process.on('uncaughtException') but to no avail.
Thanks!
Rewrite your final call like this:
function errorHandler(err) {
console.log('You had an error, ' + err);
}
first
.then(second, errorHandler);
The promise captures any exceptions that throw within it, you need to explicitly handle it.
A variation that's q specific would be:
first
.then(second)
.fail(errorHandler);
You may consider this easier to read.
I think it may be appropriate to catch the error before the declaration of the contract object. So something like this:
map(locations, function(loc) {
if(!loc.ClientId) {
console.log("Error: loc.ClientId is undefined");
} else {
var contract = {
"clientName": clients[loc.ClientId][0]
}
...
}
})
Here the error is logged to console when loc.ClientId is undefined.
It really depends what your stack trace looks like. If you're using express or restify, for example, you may actually need to listen for the uncaughtException event on your server object. The error is normally not lost; put something like this into a sample JS file:
null.f();
and you'll see a TypeError thrown, as you are expecting.
If you're not sure of the stack, log it:
console.log(new Error("this is my stack").stack);

mongodb crashed node with exception within try catch

try
p = req.params.name
Item.update('name': p, req.body , {upsert: true}, (err) ->
if err?
throw err
res.send("ok")
)
catch e
handle_error(e, "Error salvando hoja de vida.", res)
This produces an error in my code right now - that's alright, but why does my nodejs program crash even if I have a try catch here?
The error is:
MongoError: Mod on _id not allowed
(so it must be in the update call)
I am specifically looking for a way to catch an error, I already know how to get rid of it.
Ah yes, you have entered the realm of asynchronous code. The reason you pass a callback into your MongoDB calls like Item.update(..., callback) is because the MongoDB driver is written to be asynchronous. Consider this (mongoose code):
var user = User.findOne({ name: 'joe' });
doSomethingElse();
If it had structured its API like the above code then your entire application would halt until User.findOne() returned the results from the database. Your doSomethingElse() call wouldn't be invoked until the user was retrieved, even if you don't do anything with user inside doSomethingElse. This is a big no no these days and especially in node which has been written to be asynchronous as much as possible. Have a look at the following:
User.findOne({ name: 'joe' }, function (err, user) {
if (err) return console.error(err);
console.log('Do stuff with user... ;)');
});
doSomethingElse();
The above code is asynchronous. The findOne function returns immediately and doSomethingElse is able to begin even before the user is ever retrieved from the database. But of course we still want to do stuff with our user, so in order to accomplish this we pass an anonymous function in to be used as a callback. The MongoDB driver is smart enough to call that function when it's all done retrieving data.
Wrapping the above code in a try/catch would be pointless, unless you suspected the findOne function to throw an exception (Which you shouldn't. It returns immediately remember?).
try {
User.findOne({ name: 'joe' }, function (err, user) {
throw new Error("Something went wrong...");
});
} catch (err) {
console.error(err);
}
The above error would still crash your program because it happened long after findOne returned and your program moved on way beyond that precious try/catch. This is the very reason why your callback function receives an err argument. The MongoDB driver knows that if some error occurs while fetching your data it would be no good to throw an exception and call it good. This is because all this processing has happened later on subsequent trips through the event loop, having left your try/catch behind several iterations ago.
To get around this the MongoDB driver wraps its own internal synchronous code in a try/catch where it actually will handle the exception and then it invokes your callback passing in the error as the first argument. This allows you to check that argument and handle any errors within your callback.
I wrote an entire blog post explaining callbacks, as well as another way of handling asynchronous code called "promises" and I think it would help clarify some things for you :) http://codetunnel.io/what-are-callbacks-and-promises
I hope that helps answer your question.
Maybe I'm wrong (because I don't know Coffeescript), but I suppose the problem is, that your try/catch is outside the callback function. The catch doesn't affect your err -> so the exception is not caught by you, but by node.js.
If I'm wrong, could you perhaps provide the compiled JavaScript code?
Edit
Usually one would handle the error more like this (without try/catch):
Item.update('name': p, req.body , {upsert: true}, (err) ->
if err?
log.error('error updating Item name=' + name)
res.status(500).end()
return
res.send("ok")
)
Probably your handle_error will do this already.
When programming in node.js, I use try/catch only for JSON.parse or if I have a lot of unchecked input which might have wrong types or might be null and I'm too lazy to check all input manually. Surrounding asynchronous functions with try/catch is only helpful if the function has programming errors (e.g. not checking your input correctly).

Resources