说我有这个脚本:
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.');
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,如果出现错误,我想停止脚本执行任何下游功能.
我已经设法通过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.');
}
Run Code Online (Sandbox Code Playgroud)
但那是"正确"做事的方式吗?
备择方案
我也看过使用process.exit();和的例子process.exit(1);,但这给了我一个502 Bad Gateway错误(我假设因为它杀了节点?).
而且callback();,这只是给了我一个'未定义'的错误.
什么是在任何给定点停止node.js脚本并阻止任何下游函数执行的"正确"方法?
小智 38
使用a return是停止执行函数的正确方法.你是正确的process.exit()会杀死整个节点进程,而不是仅仅停止那个单独的函数.即使您使用的是回调函数,也需要将其返回以停止执行函数.
ASIDE:标准回调是一个函数,其中第一个参数是错误,如果没有错误则为null,因此如果您使用回调,则上面的内容如下所示:
var thisIsTrue = false;
exports.test = function(request, response, cb){
if (thisIsTrue) {
response.send('All is good!');
cb(null, response)
} else {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}
console.log('I do not want this to happen. If there is an error.');
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*yal 24
您可以使用process.exit()立即强制终止nodejs程序。
您还可以传递相关退出代码来指示原因。
process.exit() //default exit code is 0, which means *success*
process.exit(1) //Uncaught Fatal Exception: There was an uncaught exception, and it was not handled by a domain or an 'uncaughtException' event handler
process.exit(5) //Fatal Error: There was a fatal unrecoverable error in V8. Typically a message will be printed to stderr with the prefix FATAL ERROR
您应该使用return,这将帮助您对发生的事情做出反应。这是一个更简洁的版本,基本上首先验证您要验证的任何内容,而不是将所有内容封装在 if{}else{} 语句中
exports.test = function(request, response, cb){
if (!thisIsTrue) {
response.send('ERROR! ERROR!');
return cb("THIS ISN'T TRUE!");
}
response.send('All is good!');
cb(null, response)
console.log('I do not want this to happen. If there is an error.');
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用 throw
exports.test = function(request, response, cb){
if (!thisIsTrue) {
response.send('ERROR! ERROR!');
cb("THIS ISN'T TRUE!");
throw 'This isn\'t true, perhaps it should';
}
response.send('All is good!');
cb(null, response)
console.log('I do not want this to happen. If there is an error.');
}
Run Code Online (Sandbox Code Playgroud)
最后,会阻止整个应用程序进一步执行的示例:
a) 抛出错误,这也将帮助您调试应用程序(不会完全停止应用程序,如果test()函数在 中包装try{}catch(e){}):
throw new Error('Something went wrong')
b) 停止脚本执行(适用于 Node.js):
process.exit()