[英]get exception from func that has func as an param
I have one function a that accepts a function func
as an argument and returns a new function 我有一个函数a接受函数
func
作为参数并返回一个新函数
how to catch error thrown from a function in function a, because i want to return null from function a when function returns exception. 如何捕获函数a中的函数引发的错误,因为当函数返回异常时,我想从函数a返回null。 In below case also
在下面的情况下
Return a new function that calls func
wrapped in a try..catch
, and remembers whether it has error'd before: 返回一个新函数,该函数调用包装在
try..catch
func
,并记住它之前是否有错误:
const a = func => {
let hasThrown = false;
return function () {
if (hasThrown) {
return null;
}
try {
return func(...arguments);
} catch (e) {
console.error(e);
hasThrown = true;
return null;
}
};
};
const a = func => { let hasThrown = false; return function() { if (hasThrown) { return null; } try { return func(...arguments); } catch (e) { console.error(e); hasThrown = true; return null; } }; }; const getMyName = (name) => { if (name === "jos") { throw new Error(`${name} is wrong`); } return `${name} is yummy`; }; const getName = a(getMyName); console.log(getName("harry")); console.log(getName("garry")); console.log(getName("jos")); console.log(getName("jon"));
You could surround getCount()
inside try
and catch
您可以将
getCount()
包围在try
和catch
try {
getCount()
}
catch(e){
console.log(e)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.