Node.js / Express - 找不到页面时出现错误

时间:2011-10-03 22:59:45

标签: javascript node.js express mongoose

我在Node.js中使用以下控制器/路由定义(使用Express和Mongoose)。当用户请求不存在的页面时,处理错误的最简洁方法是什么?

  app.get('/page/:pagetitle', function(req, res) {
      Page.findOne({ title: req.params.pagetitle}, function(error, page) {
          res.render('pages/page_show.ejs',
            { locals: {
                title: 'ClrTouch | ' + page.title,
                page:page
            }
          });
      });
  });

它目前破坏了我的应用。我相信因为我没有对错误做任何事情我只是把它传递给视图就像成功一样?

TypeError: Cannot read property 'title' of null

非常感谢。

2 个答案:

答案 0 :(得分:47)

查看明确的error-pages示例。原则是首先注册您的应用程序路由,然后为所有其他未映射到路由的请求注册一个catch all 404处理程序。最后,注册了一个500处理程序,如下所示:

// "app.router" positions our routes 
// specifically above the middleware
// assigned below

app.use(app.router);

// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

app.use(function(req, res, next){
  // the status option, or res.statusCode = 404
  // are equivalent, however with the option we
  // get the "status" local available as well
  res.render('404', { status: 404, url: req.url });
});

// error-handling middleware, take the same form
// as regular middleware, however they require an
// arity of 4, aka the signature (err, req, res, next).
// when connect has an error, it will invoke ONLY error-handling
// middleware.

// If we were to next() here any remaining non-error-handling
// middleware would then be executed, or if we next(err) to
// continue passing the error, only error-handling middleware
// would remain being executed, however here
// we simply respond with an error page.


app.use(function(err, req, res, next){
  // we may use properties of the error object
  // here and next(err) appropriately, or if
  // we possibly recovered from the error, simply next().
  res.render('500', {
      status: err.status || 500
    , error: err
  });
});

答案 1 :(得分:3)

Node.JS的一个主要问题是没有干净的错误捕获。传统方法通常用于每个回调函数,如果存在错误,则第一个参数为not null,例如:

function( error, page ){
   if( error != null ){
       showErrorPage( error, req, res );
       return;
   }
   ...Page exists...
}

过了很多回调,事情会变得很难看,我推荐使用像async这样的东西,这样如果有一个错误,就会直接进入错误回调。

编辑:您也可以使用express error handling