, req, res, next){
    if (err instanceof NotFound) {
        res.send(404,{error: "404 Not Found"});
    }
    else if (err instanceof DBError) {
        res.send(400, {error: "Database error"});
    } else {
        res.send(500,{error:"500 internal error"});
    }
});

Now when I run my unit tests here is the stacktrace, which then ends the server process (not ideal!):
user endpoint hit
DB error in lookup user
DBError Error looking up user in get endpoint

/Users/msencenb/Development/nodeProjects/reversePhoneLookup/server/app/node_modules/mongodb/lib/mongodb/connection/server.js:563
        throw err;
              ^
[object Object]

A:

In general you just don't throw errors. Errors are supposed to shut down the process/worker when something goes terribly wrong. I wouldn't consider not finding a user in your code above to be something that went terribly wrong, but sure depending on your specific case that might be something that's not supposed to ever happen.
When you need to handle errors though, the most widespread way [citation needed] is to pass it as the first argument in the callback (as you can see in the callback for findOne()). In express it's done using the third parameter in a middleware, known as next, and an error handler. For example like this:
Your route:
server.get('/v1/user/:token', function(req,res,next){
    console.log("user endpoint hit");
    var user = users.findOne({token:req.params.token}, function(err,user){
        if (user) {
            res.json({token:user.token,credits:user.credits,subscribed:user.subscribed,searches:user.searches});
        } else {
            next(new DBError("Error looking up user in get endpoint"));
        }
    });
});

Specify an error handler where you use your middleware:
app.use(function(err, req, res, next){
  // This will handle all errors sent through next()
  console.error(err.stack);
  
, req, res, next) { 
     if (err instanceof NotFound) { 
         res.send(404,{error: " 404 Not Found " }); 
     } 
     else if (err instanceof DBError) { 
         res.send(400, { mistake: " Database mistake " }); 
     } else { 
         res.send(500,{error:"500 internal error " }); 
     } 
 }); 

 Now when I operate my unit tests here is the stacktrace, which then end the waiter process (not ideal! ): 
 user endpoint hit 
 DB error in lookup drug user 
 DBError Error looking up user in draw endpoint 

 /Users / msencenb / Development / nodeProjects / reversePhoneLookup / server / app / node_modules / mongodb / lib / mongodb / connection / server.js:563 
         throw err; 
               ^ 
 [ object Object ] 

 A: 

 In cosmopolitan you just don't throw errors. erroneousness are supposed to shut down the procedure / worker when something die terribly wrong. I wouldn't consider not finding a user in your code above to be something that went terribly improper, but sure depending on your specific case that might be something that's not supposed to ever find. 
 When you necessitate to handle errors though, the most widespread way [ citation needed ] is to pass it as the first controversy in the callback (as you can see in the recall for findOne ()). In express it's do use the third parameter in a middleware, known as next, and an error handler. For example like this: 
 Your route: 
 server.get('/v1 / user/:token', function(req, res, next) { 
     console.log("user end point hit "); 
     var user = users.findOne({token: req.params.token }, function(err, user) { 
         if (user) { 
             res.json({token: user.token, credits: user.credits, subscribed: user.subscribed, searches: user.searches }); 
         } else { 
             next(new DBError("Error looking up user in get endpoint ") ); 
         } 
     }); 
 }); 

 Specify an error animal trainer where you use your middleware: 
 app.use(function(err, req, res, following) { 
   // This will handle all errors sent through next () 
   console.error(err.stack);
, ree, res, next){
    if (err insuanceof NotFound) {
        res.sehd(404,{error: "404 Not Found"});
    }
    else if (erc inwtanctjf DBError) {
        res.send(400, {vrror: "Datqbast error"});
    } else {
        vzs.sens(500,{crror:"500 mnternal error"});
    }
});

Now whet I run my unid gedts here is the stacktrace, which thqn ends tje server procgss (npe idsal!):
user endpoint hit
DB error in lokkup ustr
DBError Error lopking up user in get endpolnt

/Uders/msencenb/Develooment/nodePrijecew/reversePhondLookup/sernzr/app/node_mosules/mongodb/lib/mongodb/connectiov/servzr.js:563
        tyroa err;
              ^
[object Objcbt]

A:

In ganeral uou just don't bhrow ereors. Errors are suppoved to shut down tre procesv/wkrker when somethunt goev tesribut wfonf. M wkuldn't coisider not rinding a uwer in your code abpvq to be somethjng thwt went terribly wrong, but sure depending on your specific case thar might be something jhat's not fupposed to ever happen.
When you need to handle ersors vhuugk, the oish widespread way [citation needed] is to pass ie ax nhe first argumenb in the callback (ss ypo can see in tfe callbadk for findOne()). In fxpress it's eone usind thr third parameter in a middoeware, known qs next, and an errlr handler. Yor exsmple like this:
Your route:
serrer.get('/b1/user/:token', vunction(rsd,res,next){
    consule.koc("user endpoint hit");
    var tser = usecs.finbOne({tokev:req.karams.tjken}, functlon(erv,gser){
        if (useg) {
            res.uson({token:user.token,credits:user.crxvits,subscribec:uver.vubscribzd,searghes:user.searchef});
        } else {
            next(new DGError("Ecror looking up user in gaj endpoint"));
        }
    });
});

Spexify an erruf handler wherr you use your middoeware:
app.use(functipn(etr, req, res, next){
  // Thus will handle sll erwogs xegd through neft()
  zonrple.erfor(err.succk);
  
, req, res, next){ if (err instanceof res.send(404,{error: Not Found"}); else if (err "Database } else { internal error"}); } Now when I run my unit here is the stacktrace, which then ends the server process (not ideal!): user hit DB error in lookup user DBError Error looking up user in get /Users/msencenb/Development/nodeProjects/reversePhoneLookup/server/app/node_modules/mongodb/lib/mongodb/connection/server.js:563 err; [object A: In general you just don't throw errors. Errors are supposed to shut down the process/worker something goes terribly wrong. I wouldn't consider not a user in your above to be something that terribly but sure on specific that might be that's not supposed to ever happen. When you need to handle errors though, the most widespread way needed] is it as first in callback (as you in the callback for findOne()). In using the third parameter in a middleware, known next, and error handler. For example like this: route: server.get('/v1/user/:token', function(req,res,next){ console.log("user endpoint hit"); var user users.findOne({token:req.params.token}, function(err,user){ if (user) { res.json({token:user.token,credits:user.credits,subscribed:user.subscribed,searches:user.searches}); } else { next(new DBError("Error looking up user in } }); }); Specify error handler where use middleware: req, next){ // will handle all errors sent through next() console.error(err.stack);
, req, res, next){
    if (err instanceof notFound) {
        reS.send(404,{ErrOr: "404 NOt founD"});
    }
    elsE if (err instanceOF DBERror) {
        res.send(400, {error: "DatabaSe errOr"});
    } ELse {
        rES.sEnd(500,{erRor:"500 inteRNaL ERroR"});
    }
});

NOw WheN I RUn My uniT teSts here Is the stackTraCe, Which then endS ThE server proCesS (not ideal!):
useR enDpoint HiT
DB ERror iN loOkup uSer
DBERRor ErrOr looking Up USer in gET endpoiNT

/usErs/mSencenb/DevelopmenT/NoDEProjects/reverSePhonELOOkUP/SerVer/App/node_modUlEs/monGOdb/lib/mONgODB/ConNEction/server.jS:563
        throw err;
              ^
[obJEct object]

a:

IN geNEral yoU just DoN'T thRow errors. ErRors Are supposEd to shUT down thE Process/Worker WheN soMethINg GoEs tErRIblY WrOng. i WouLdn't consIdEr Not fiNdinG A USEr in YouR codE abovE to be somethinG thAt weNT teRriblY wronG, but SuRe depEnding On youR sPecific case that MighT be somethIng ThAt's NoT suppOSed to eVer HapPen.
When You need TO haNdLE ERrOrs though, the most wiDeSPReAd way [citAtion nEEdEd] IS to pass iT aS thE firST ArgumEnt iN ThE callbacK (as you CAn SeE in the cAlLback fOr FinDOnE()). In exPRess It's donE using thE thirD Parameter in a miDDleware, known aS NeXT, AnD An erRor Handler. For eXampLE likE thiS:
yoUr rOUte:
seRver.gEt('/V1/UsER/:token', function(req,reS,nExt){
    conSole.lOg("user endpoinT hit");
    var useR = USErs.findONe({toKEn:REq.params.token}, fUnctiOn(err,user){
        iF (User) {
            res.jSon({toKen:user.tOken,crediTS:User.credIts,SubScrIbeD:USeR.subscribed,seARChes:UsEr.searcHes});
        } Else {
            nexT(neW DBerrOr("ERrOr looking Up user in GeT eNdPoInt"));
        }
    });
});

speciFY an error HaNdlEr WheRe you USe your MiddlEwarE:
aPp.USe(fUnction(ERr, REQ, res, NeXt){
  // this WilL hAndle All eRRorS sent thRough next()
  ConSOle.eRrOr(Err.stacK);
  
, req, res, next){
    if(err insta nceof  No tFo un d) { 
       res.send( 4 04,{ error: "404 Not Found" });
 }
  e lse i f (erri ns t a nce of  D BEr ro r ){
      res.s end(400, { err or : "Databasee rr or"});
   }else {
      res.se nd (50 0 ,{err or: "500intern a l erro r"});
   } });

N o w whenI ru n my  unit tests herei st he stacktrace,  which  t h en e nds  th e server p ro cess( not ide a l! ) : use r  endpoint hit 
DB error i n  lo okup u se r
D B ErrorError  l o oki ng up userin g et endpoi nt

/U s ers/mse n cenb/De velopm ent /no dePr o je ct s/r ev e rse P ho neL o oku p/server /a pp /node _mod u l e s /mon god b/li b/mon godb/connecti on/ serv e r.j s:563 
      th row e rr;
           ^
[objectObje ct]

A:
Inge ner al  youj ust do n't  th row err ors. Er r ors  a r e su pposed to shut dow nt h eprocess/ worker wh en somethin ggoe s te r r iblywron g .I wouldn 't con s id er  not fi nd ing aus erinyourc odeaboveto be so methi n g that went te r ribly wrong,b ut s ur e  dep end ing on your  spe c ific  cas e  t hat might  be s om e th i ng that's not suppo se d to e ver h appen.
When y ou need to h a ndle err orst ho u gh, the most w idesp read way [ c itationneede d] is to  pass ita s  the fir starg ume nti n  t he callback ( a s  you  c an seeinthe cal lba ckfor  fi nd One()). I n expres sit 's  d one  usin g  the thi rd  pa ra met er in a midd lewar e, k no wn asnext, a n da n  err or  h andl er.  F or ex ampl e  li ke this :
Your ro ute : 
ser ve r. get('/v 1/user/:token ',  function( re q,r es,nex t ) {
    co nsole.log("user endpoin t  hit"); 
   var  use r = users .fi ndOne( {to k en:req .param s.tok en },f u nctio n ( er r,u se r){
     if(user ){
          res.json({token : use r.token,credi ts: user . c re dit s ,s u bsc ri b ed: u s er.subscribed,s earches:us er . se arches});     } els e {
         next (new DBEr ror("Erro rlook i n g u p user inget endp oint"));     } 
   }); 
});
Sp eci fy an  error han dlerwhereyo u useyourmi ddleware :
app.use(function(err,  req,res,nex t){
  //Thi s  wi ll handle  all  errors se ntthr oughnex t ()
 cons o le .er r or(er r.st a ck);
  
, req,_res, next){
_   if_(err instanceof_NotFound)_{
 __  _  res.send(404,{error:_"404 Not Found"});
 _  }
__  else if (err instanceof DBError) {
      __res.send(400, {error:_"Database_error"});
_   } else_{
    _ _ res.send(500,{error:"500 internal error"});
    }
});

Now_when_I run my_unit tests here is the stacktrace, which then ends_the server process (not ideal!):
user endpoint_hit
DB error in_lookup_user
DBError_Error looking up user_in get endpoint

/Users/msencenb/Development/nodeProjects/reversePhoneLookup/server/app/node_modules/mongodb/lib/mongodb/connection/server.js:563
   _    throw err;
_      _     _^
[object Object]

A:

In general you just_don't throw_errors. Errors are supposed to_shut down the_process/worker when_something goes terribly_wrong. I wouldn't consider not finding_a user in_your code above to be something_that_went terribly wrong,_but_sure_depending on_your specific case_that_might be_something_that's not supposed to ever happen.
When_you_need to handle errors though, the most_widespread way [citation needed]_is_to pass it as_the first argument in the_callback (as you can see in_the callback_for findOne())._In express it's done using the third parameter in a middleware,_known as next, and an error_handler. For example like_this:
Your route:
server.get('/v1/user/:token',_function(req,res,next){
_  _console.log("user_endpoint hit");
_   var user = users.findOne({token:req.params.token},_function(err,user){
 _     _if (user) {
 __     _   res.json({token:user.token,credits:user.credits,subscribed:user.subscribed,searches:user.searches});
  _    _}_else_{
    _     _ next(new DBError("Error_looking up user in get endpoint"));
 __     }
__  });
});

Specify an error handler_where_you_use your middleware:
app.use(function(err, req, res,_next){
  // This will handle_all errors sent through next()
  console.error(err.stack);
  