有人可以说明在node.js Express应用程序中合适的时间抛出以下错误:
throw new Error('my error');
或通过通常标有“ next”的回调传递此错误,如下所示:
next(error);
您能否解释一下在Express应用程序中它们各自将做什么?
例如,这是一个处理URL参数的Express函数:
app.param('lineup_id', function (req, res, next, lineup_id) {
// typically we might sanity check that user_id is of the right format
if (lineup_id == null) {
console.log('null lineup_id');
req.lineup = null;
return next(new Error("lineup_id is null"));
}
var user_id = app.getMainUser()._id;
var Lineup = app.mongooseModels.LineupModel.getNewLineup(app.system_db(), user_id);
Lineup.findById(lineup_id, function (err, lineup) {
if (err) {
return next(err);
}
if (!lineup) {
console.log('no lineup matched');
return next(new Error("no lineup matched"));
}
req.lineup = lineup;
return next();
});
});
在注释行中“ //我应该在这里创建自己的错误吗?” 我可以使用“引发新的Error('xyz')”,但这究竟会做什么?为什么通常最好将错误传递给回调“ next”?
另一个问题是-在开发过程中,如何在控制台以及浏览器中显示“引发新的Error('xyz')”?
通常,express遵循传递错误而不是抛出错误的方式,对于程序中的任何错误,您都可以将错误对象传递给'next',还需要定义错误处理程序,以便可以处理传递给next的所有错误。适当地
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句