我有三个函数,每个函数都调用另一个函数。
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);
}
要处理in中的错误one
,请使用try
/ catch
in 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] 删除。
我来说两句