簡體   English   中英

Node.js / Express - 找不到頁面時出現錯誤

[英]Node.js/Express - Render error when page not found

我在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

非常感謝。

查看express 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
  });
});

Node.JS的一個主要問題是沒有干凈的錯誤捕獲。 傳統方法通常用於每個回調函數,如果存在錯誤,則第一個參數為not null,例如:

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

一段時間后回調過多會導致事情變得難看,我建議使用像async這樣的東西,這樣如果有一個錯誤,就會直接進入錯誤回調。

編輯:您還可以使用快速錯誤處理

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM