Node.js/Express - 找不到页面时呈现错误
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 Express 错误页面 示例。原则是首先注册您的应用程序路由,然后为所有其他未映射到路由的请求注册一个捕获所有 404 处理程序。最后注册一个500的handler,如下:
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:
Node.JS 的主要问题之一是没有干净的错误捕获功能。传统的方法通常是对于每个回调函数,如果出现错误,第一个参数不为空,因此例如:
回调次数过多,一段时间后事情会变得丑陋,我建议使用类似 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:
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.