我有一个巨大的解析功能,如果文件正确,它运行良好,但我无法正确处理错误。
function parse (pathname, callback){
//Some variables
fs.open(pathname, 'r', function(err, fd){
if (err){console.log('Error Opening the file'); callback(-1);}
console.log('Begin the parsing');
//Do the parsing
但是如果我给出一个无效的路径名,我会收到错误消息,并且该函数会一直持续到读取时发生致命错误。
我认为回调结束了这个功能,但似乎我错了。
我可以这样做:
function parse (pathname, callback){
//Some variables
fs.open(pathname, 'r', function(err, fd){
if (err){console.log('Error Opening the file'); callback(-1);}
else{
console.log('Begin the parsing');
//Do the parsing
但是它中有很多错误处理,而且功能非常庞大。
在其他代码中我经常看到
if (err){throw err;}
但是我从来没有做过任何事情,甚至是简单的事情,所以我也想避免这样做,如果我不处理它,最终关闭应用程序,我也不想要。
有没有一种巧妙的方法让我以另一种方式处理错误?
答案 0 :(得分:1)
您可以使函数parse
返回,这将中断函数执行。
if (err) {
console.log('Error opening the file');
callback(-1);
return; // Alternatively return false or anything you want
}
调用callback(-1)
不会结束该函数,因为它是一个简单的函数调用,就像console.log()
或任何其他函数一样。