带有Express的Node.js-抛出错误与下一个错误 [英] Node.js with Express - throw Error vs next(error)
问题描述
有人可以说明在node.js Express应用程序中合适的时间抛出诸如此类的错误吗?
Can someone expound on the times when it's appropriate in a node.js Express app to throw an error like so:
throw new Error('my error');
或通过通常标有"next"的回调传递此错误,如下所示:
or to pass this error on via the callback usually labelled 'next' like so:
next(error);
您能否解释一下在Express应用程序中它们各自将做什么?
and could you please explain what each of them will do in the context of an Express app?
例如,这是一个处理URL参数的快速函数:
for example, here is an express function dealing with URL parameters:
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"更好?
In the line commented "//should I create my own error here?" I could used "throw new Error('xyz')", but what exactly would that do? Why is it usually better to pass the error to the callback 'next'?
另一个问题是-在开发过程中,如何在控制台以及浏览器中显示引发新错误('xyz')"?
Another question is - how do I get "throw new Error('xyz')" to show up in the console as well as the browser when I am in development?
推荐答案
一般来说,express遵循传递错误而不是抛出错误的方式,对于程序中的任何错误,您都可以将错误对象传递给'next',需要定义错误处理程序,以便可以正确处理传递给next的所有错误
In general express follows the way of passing errors rather than throwing it, for any errors in the program you can pass the error object to 'next' , also an error handler need to be defined so that all the errors passed to next can be handled properly
http://expressjs.com/guide/error-handling.html
这篇关于带有Express的Node.js-抛出错误与下一个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!