我正在使用以下可以正常工作的功能,但是我在错误处理方面存在一些问题
例如
我想捕获所有功能的通用错误
如果fn1
或fn2
返回任何错误,该函数应抛出“发生一般错误”
这是我需要的
如果getData2
没有特定的属性值(请参见if),则返回uniq错误,uniq error occurred
而不是一般错误...
这是工作示例
https://jsfiddle.net/8duz7n23/
async function func1() {
try {
const data = await getData1()
console.log(data)
const data2 = await getData2();
if (!data2.url === !"https://test2.com") {
throw new Error("uniq error occurred ")
}
return data2.url
} catch (e) {
throw new Error("generic error occurred ")
}
}
async function getData1() {
return "something"
}
async function getData2() {
return {
url: "http://test.com"
}
}
func1().then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});
现在,如果我抛出uniq错误,则catch将引发一般错误。
我希望万一func2
出现一些错误,它仍然会丢弃一般错误,但是即使doenst具有正确的url,也要一路向上拖动uniq error
...
有没有更干净的方法可以在nodejs中做到这一点?
我不想对捕获中的消息使用if语句...
我想该遗嘱抛出到上层的功能,而不是捕捉
为了将错误传播到“上层”,您必须将其再次放入catch块中。
您可以添加您的自定义错误类型,并检查该错误是否是您要查找的错误。
class UrlMismatchError extends Error {
name="UrlMismatchError"
}
async function func1() {
try {
const data = await getData1()
console.log(data)
const data2 = await getData2();
if (data2.url !== "https://test2.com") {
throw new UrlMismatchError("uniq error occured");
}
return data2.url
} catch (e) {
if (e instanceof UrlMismatchError) {
throw e;
} else {
// handle generic errors
throw new Error("generic error occured");
}
}
}
async function getData1() {
return "something"
}
async function getData2() {
return {
url: "http://test.com"
}
}
func1().then(result => {
console.log(result);
}).catch(error => {
console.error(error.message);
});
我不想对捕获中的消息使用if语句...
我希望将遗嘱扔给上级职能部门而不是抓住
不,您不能那样做,因为javascript不是Java,因此您不能执行以下操作:
// the code snippet below wont work
try {
doSomething();
} catch(UrlMismatchError e) {
// propagate error to the upper level
throw e;
} catch(Error e) {
// handle all the other errors
console.log(e);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句