从以func为参数的func中获取异常

我有一个函数a接受一个函数func作为参数并返回一个新函数

如何捕获函数a中的函数引发的错误,因为当函数返回异常时,我想从函数a返回null。在下面的情况下


慕容3067478
浏览 261回答 2
2回答

互换的青春

返回一个新函数,该函数调用func包装在中的try..catch,并记住该函数之前是否有错误: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"));

慕桂英3389331

你可以围绕getCount()内部try和catchtry {    getCount()} catch(e){    console.log(e)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript