- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我在 Node.js 中有以下 Controller /路由定义(使用 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
}
});
});
});
它目前破坏了我的应用程序。我相信因为我没有对错误做任何事情,我只是将它传递给 View ,就像成功一样?
TypeError: Cannot read property 'title' of null
非常感谢。
最佳答案
查看 express error-pages例子。原则是首先注册您的应用程序路由,然后为所有其他未映射到路由的请求注册一个 catch all 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
});
});
关于javascript - Node.js/Express - 找不到页面时呈现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7641622/
例如,我有一个父类Author: class Author { String name static hasMany = [ fiction: Book,
代码如下: dojo.query(subNav.navClass).forEach(function(node, index, arr){ if(dojo.style(node, 'd
我有一个带有 Id 和姓名的学生表和一个带有 Id 和 friend Id 的 Friends 表。我想加入这两个表并找到学生的 friend 。 例如,Ashley 的 friend 是 Saman
我通过互联网浏览,但仍未找到问题的答案。应该很容易: class Parent { String name Child child } 当我有一个 child 对象时,如何获得它的 paren
我正在尝试创建一个以 Firebase 作为我的后端的社交应用。现在我正面临如何(在哪里?)找到 friend 功能的问题。 我有每个用户的邮件地址。 我可以访问用户的电话也预订。 在传统的后端中,我
我主要想澄清以下几点: 1。有人告诉我,在 iOS 5 及以下版本中,如果您使用 Game Center 设置多人游戏,则“查找 Facebook 好友”(如与好友争夺战)的功能不是内置的,因此您需要
关于redis docker镜像ENTRYPOINT脚本 docker-entrypoint.sh : #!/bin/sh set -e # first arg is `-f` or `--some-
我是一名优秀的程序员,十分优秀!