gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:05 25 4
gpt4 key购买 nike

我注意到虽然生成器内部出现错误,但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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com