node.js - Express.js 在生成器内部出错时继续加载和加载

标签 node.js express mongoose

我注意到虽然生成器内部出现错误,但express.js 仍在继续处理而不停止它。所以,我无法找到实际的错误。我的问题是:当生成器出现错误时,如何停止express.js并输出错误。

我的代码

Controller.js

const mongoose = require('mongoose');
const {wrap: async} = require('co');
const Post = require('../models/Post');
//.... there are more modules.

const getPosts = async(function* (req, res) {
  const page = (req.query.page > 0 ? req.query.page : 1) - 1;
  const limit = 5;
  const options = {
    limit: limit,
    page: page
  };

  const posts = yield Post.list(options);
  const count = yield Post.count();
  console.log(posts);

  res.render('posts/index', {
    title: 'Home',
    posts: posts,
    page: page + 1,
    pages: Math.ceil(count / limit)
  });
});

app.get('/', getPosts);

Post.js

//.. more codes

postSchema.static.list = function (options) {
  const criteria = options.criteria || {};
  const page = options.page || 0;
  const limit = options.limit || 30;
  return this.find(criteria)
    .populate('user', 'name userlogin profile email')
    .sort({ createdAt: -1 })
    .limit(limit)
    .skip(limit * page)
    .exec();
};

最佳答案

Post.js 中存在拼写错误。 postSchema.static.list 应该是 postSchema.statics.list (静态不是静态)。

尝试将 yield 包装在 try 和 catch 中。

const getPosts = async(function* (req, res, next) {
  const page = (req.query.page > 0 ? req.query.page : 1) - 1;
  const limit = 5;
  const options = {
    limit: limit,
    page: page
  };
  try {
    const posts = yield Post.list(options);
    const count = yield Post.count();
    console.log(posts);

    res.render('posts/index', {
      title: 'Home',
      posts: posts,
      page: page + 1,
      pages: Math.ceil(count / limit)
    });
  }catch(err){
    next(err);
  }
});

关于node.js - Express.js 在生成器内部出错时继续加载和加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38548670/

相关文章:

javascript - 如果 JSON 中的键有空值,则发送错误状态(AJAX、Node 和 Express)

javascript - 无法读取未定义的属性 'user_first_name'

json - Elasticsearch js 批量索引类型错误

node.js - $Waterline ODM的pull函数用于更新Mongo数据库

javascript - 将数组元素写入不同的文件

javascript - GET 变量名称包含破折号会为 NodeJS Express 的 req.query 带来问题吗?

json - Node.js 中的正文解析不会转义请求正文中的换行符? JSON

javascript - 如何在不选择模式配置参数的情况下使用 Mongoose 在 MongoDB 模式实例化的关联数组/对象中执行 foreach?

javascript - Mongoose 模式无法读取未定义的属性 'password'

node.js - .jsx 总是在 React 项目中吗?