如何在JavaScript中进行正确的错误处理?

尼古拉斯·斯塔德勒

我有三个函数,每个函数都调用另一个函数。

function one() {
   two();
}

function two() {
   three();
}

function three() {
   // here an error will occur, and then should be resolved
   try {
      // whatever
   } catch (e) {
      // here should the error be resolved;
   }

}

现在我的问题是,如何实现在调用one()时,将在three()中发生的错误传递给函数two(),然后传递给函数one(),然后该函数仅对错误进行处理能够。我用回调函数尝试了一下,但是用try / catch却没有用,但是由于我是所有解决错误的新手,所以我可能搞砸了。在这里,我尝试进行回调并尝试捕获:

function one() {
   try {
     two();
   } catch (e) {
     console.log(e);
   }
}

function two() {
  try {
   three();
  } catch (e) {
    return e;
  }
}

function three() {
   // here an error will occur, and then should be resolved
   try {
      // whatever
   } catch (e) {
      return new Error("ERROR");
   }

}

回调:

function one(function (err) {
  if (err == "ERROR") { 
       console.log("everything worked");
  } else { throw err }
});



function two(callback) {
  try {
     three(callback);
  } catch (e) {
     return callback(e);
  }

 function three(callback) {
     try {
        //whatever
    } catch (e) {
      return callback(new Error("ERROR");
    }
  }

也许我应该解释我的工作。我有一个函数,可以通过文件名从文件中读取数据,然后返回数据。另一个函数接收该数据并对其进行操作,但是我只专注于接收。那也有参数路径。基本上,它看起来像这样:

function main() {
  try {
manipulateData("C:\\......");//That file doesnt exist, so an error will occur
   } catch (e) {
      return console.log("Error": e);
   }
}

function manipulateData(path) {
    var data = getUserdata(path);
    .....
}

function getUserdata(path) {
    return fs.readFileSync(path);
}
TJ人群

要处理in中的错误one,请使用try/ catchin one

function one() {
    console.log(`in one`);
    try {
        two();
    } catch (e) {
        console.log(`handling error "${e.message}...`);
        console.log("continuing work...");
    }
}

function two() {
    console.log(`in two`);
    three();
}

function three() {
    console.log(`in three`);
    // Error is caused here:
    null.example();
}

one();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在BNFC中进行正确的错误处理?(C ++,Flex,Bison)

如何在Python中进行用户输入错误处理?

如何在codeigniter php中进行连接错误处理

如何在带有错误处理的 for 循环中进行迭代

如何在Apache Camel Rest API中进行自定义错误处理?

如何在 React js 功能组件中进行错误处理

如何在Rust中进行错误处理以及常见的陷阱?

如何正确重构Java方法以进行正确的错误处理

在缩小的文件中进行错误处理

如何使用 async/await 进行正确的错误处理

正确的错误处理 - 在 javascript/Ionic 中

写入数据时在std :: ofstream中进行错误处理

快速在ReactiveCocoa中进行flattenMap和错误处理

用Express在Node JS中进行简单的错误处理?

如何正确重构错误处理?

如何使用MetaTrader4错误代码刷新进行正确的错误处理?

Python 3 Pandas如何在两个'_'之间提取字符串,并在DF中进行错误处理?

如何在Node JS中正确实现500错误的错误处理

如何在全局错误处理程序中正确重定向

如何在异步/等待情况下正确实现错误处理

如何在使用NodeJS进行错误处理时使用CoffeeScript源映射?

Play框架:如何实施正确的错误处理

如何在python中进行异常处理?

如何在Android中进行图像处理?

如何在pytorch中进行并行处理

如何在FastAPI中进行多重处理

如何在C ++中进行哈希处理

matInput 如何对 valuechange 订阅的输入进行错误处理

如何使用 async/await 进行错误处理而不必等待