You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
app.get('/path/:id(\\d+)',function(req,res,next){// please note: "next" is passedif(req.params.id==0)// validate paramreturnnext(newError('Id is 0'));// go to first Error handler, see below// Catch error on sync operationletdata;try{data=JSON.parse('/file.json');}catch(err){returnnext(err);}// If some critical error then stop applicationif(!data)thrownewError('Smth wrong');// If you need send extra info to Error handler// then send custom error (see Appendix B)if(smth)next(newMyError('smth wrong',arg1,arg2));// Finish request by res.render or res.endres.status(200).end('OK');});// Be sure: order of app.use have matter// Error handlerapp.use(function(err,req,res,next){if(smth-check,e.g.req.url!='POST')returnnext(err);// go-to Error handler 2.console.log(req.url,err.message);if(req.xhr)// if req via ajax then send json else render error-pageres.json(err);elseres.render('error.html',{error: err.message});});// Error handler 2app.use(function(err,req,res,next){// do smth here e.g. check that error is MyErrorif(errinstanceofMyError){console.log(err.message,err.arg1,err.arg2);}res.end();});// Appendix A// "In Express, 404 responses are not the result of an error,// so the error-handler middleware will not capture them."// You can change it.app.use(function(req,res,next){next(newError(404));});// Appendix B// How to define custom errorletutil=require('util');functionMyError(message,arg1,arg2){this.message=message;this.arg1=arg1;this.arg2=arg2;Error.captureStackTrace(this,MyError);}util.inherits(MyError,Error);MyError.prototype.name='MyError';