Express.js中的自定义error handling

本指南build议通过以下代码自定义处理Express.js中的错误:

app.use(function(err, req, res, next) { // Do logging and user-friendly error message display console.error(err); res.status(500).send({status:500, message: 'internal error', type:'internal'}); }) 

它没有按预期工作:它始终启动相同的“无法GET”错误,而不是自定义的错误。 如何处理404和其他types的错误与Express?

未find或404不是默认情况下的应用程序错误,您定义的处理程序只有在任何路由的下一个参数中传递错误时才被调用。 处理404你应该使用一个没有错误的处理器

 app.use(function(req, res, next) { // Do logging and user-friendly error message display console.log('Route does not exist') res.status(500).send({status:500, message: 'internal error',type:'internal'}); }) 

注意: – 上面的处理程序应放置在所有有效的path之后,并在error handling程序之上。

但是,如果你想同时处理404和其他错误,你可以显式地为404生成错误,例如:

  app.get('/someRoute,function(req,res,next){ //if some error occures pass the error to next. next(new Error('error')) // otherwise just return the response }) app.use(function(req, res, next) { // Do logging and user-friendly error message display console.log('Route does not exist') next(new Error('Not Found')) }) app.use(function(err, req, res, next) { // Do logging and user-friendly error message display console.error(err); res.status(500).send({status:500, message: 'internal error', type:'internal'}); }) 

这样你的error handling程序也被称为没有发现错误和所有其他业务逻辑错误