当发生器内部出现错误时,Express.js会继续加载和加载

时间:2016-07-24 04:12:30

标签: 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();
};

1 个答案:

答案 0 :(得分:1)

Post.js中有拼写错误。 postSchema.static.list应为postSchema.statics.list(静态不是静态的)。

尝试在try和catch中包装yield

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