假设我有这个脚本:
var thisIsTrue = false;
exports.test = function(request,response){
if(thisIsTrue){
response.send('All is good!');
}else{
response.send('ERROR! ERROR!');
// Stop script execution here.
}
console.log('I do not want this to happen if there is an error.');
}
正如您所看到的,如果出现错误,我希望停止脚本执行任何下游函数。
我通过在发送错误响应后添加return;
来实现这一点:
var thisIsTrue = false;
exports.test = function(request,response){
if(thisIsTrue){
response.send('All is good!');
}else{
response.send('ERROR! ERROR!');
return;
}
console.log('I do not want this to happen if there is an error.');
}
但这是“正确”的做法吗?
其他选择
我也看到过使用process.exit();
和process.exit(1);
的例子,但那会导致502 Bad Gateway
错误(我猜测是因为它终止了node进程?)。
还有callback();
的方式,但那只会给我一个“未定义”的错误。
在任何给定的时刻停止一个node.js脚本并防止任何下游函数执行的“正确”方法是什么?