node.js - how to stop or exit on error with NodeJs -


i try understand how can stop or exit on error in nodejs route. in code below, check if header uid sent , if fiels group sent.

the problem nodejs continues execute rest of code if use res.end () + return; wish node js stop when display error. perhaps because not know in node js myself take badly , have work otherwise. can explain me , give me example of how should do?

var uid; var group;  if (typeof req.headers['uid'] == 'undefined' || req.headers['uid'] == '') {     res.status(404);     res.json('user_id not set');     res.end();     return; } else {     uid = req.headers['uid'];      user.find({_id:uid}).exec(function(err, data)     {         if(err){             res.status(404);             res.json('user not found');             res.end();             return;          }     }); }  if (typeof req.body.group == 'undefined' || req.body.group == '') {     res.status(500);     res.json('group not defined');     res.end();     return; } else {     group = req.body.group; } 

it unclear mean "node js stop everything". if want stop entire nodejs process, can use process.exit().

if you're trying keep code after error executing , error occurs in async callback, can't that. other code has executed.

if want serialize asynchronous operations complete 1 async operation before decide whether start next operation, need code differently. need execute second block of code within completion callback of first async operation.


one aspect of code may not understand block asynchronous:

user.find({_id:uid}).exec(function(err, data) {     if(err){         res.status(404);         res.json('user not found');         res.end();         return;      } }); 

the callback pass .exec() called sometime later. meanwhile, rest of js has executed. in addition, when return within callback doesn't return outer function, returns callback function bowels of .exec(). stops more of callback executing, has no effect @ on outer function because outer function.


so, if want .find() operation finish before execute rest of code in function, have put code inside callback function.


Comments

Popular posts from this blog

java - BeanIO write annotated class to fixedlength -

Using Java 8 lambdas/transformations to combine and flatten two Maps -

How to connect android app to App engine -