javascript - How does error handling work in node js -
i got sample node js code using expressgenerator ,which default got error handling code follows
app.use(function (req, res, next) { console.log("first callback 1"); var err = new error('not found'); err.status = 404; next(err); console.log("first callback 2"); }); app.use(function (err, req, res, next) { // set locals, providing error in development console.log("second callback"); res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render error page res.status(err.status || 500); res.render('error'); console.log("error send"); });
i've added few console.logs in error handling callbacks.what understood callbacks since didnt provided route here these 2 call backs called routes.
now in code i've added 1 route as
app.get('/login', function(req, res, next) { res.sendfile(__dirname + '/public/views/login.html'); });
now when run app , go localhost:3000/home
not there in app.js.so printing following
first callback 1 second callback error send first callback 2 first callback 1 second callback error send first callback 2
question 1:why console log getting printed twice?it should not print after firstcallback 2.
now when go localhost:3000/login
renders me login.html page route present there no console logs in server side.
question 2:why first console "first callback 1" not getting printed.since callback routes , in case since doesnt have error atleast should print first console..but not..why not doing callback??
can explain , how callbacks called here , use of next()
Comments
Post a Comment