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

发布于 2024-12-08 06:17:30 字数 573 浏览 2 评论 0原文

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

非常感谢。

I have the following controller/route definition in Node.js (using Express and Mongoose). What would be the leanest most appropriate way to handle Error when the user requests a page that does not exist?

  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
            }
          });
      });
  });

It currently breaks my app. I believe because I'm not doing anything with the error i'm just passing it to the view like a success?

TypeError: Cannot read property 'title' of null

Thanks much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

第七度阳光i 2024-12-15 06:17:30

查看 Express 错误页面 示例。原则是首先注册您的应用程序路由,然后为所有其他未映射到路由的请求注册一个捕获所有 404 处理程序。最后注册一个500的handler,如下:

// "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
  });
});

Check out the express error-pages example. The principle is to register your app routes first, then you register a catch all 404 handler for all other requests that do not map to a route. Finally, a 500 handler is registered, as follows:

// "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
  });
});
如梦亦如幻 2024-12-15 06:17:30

Node.JS 的主要问题之一是没有干净的错误捕获功能。传统的方法通常是对于每个回调函数,如果出现错误,第一个参数不为空,因此例如:

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

回调次数过多,一段时间后事情会变得丑陋,我建议使用类似 async,这样如果有一个错误,就直接进入错误回调。

编辑:您还可以使用快速错误处理

One of the major problems with Node.JS is that there is no clean error catching. The conventional way is usually for every callback function, the first argument is the not null if there is an error, so for example:

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

Things can get ugly after a while with too many callbacks, and I recommend using something like async, so that if there is one error, it goes directly to an error callback.

EDIT: You can also use express error handling.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文