如何使用try and catch捕获多个功能来捕获错误?

时间:2019-01-03 18:02:44

标签: javascript arrays angular try-catch

我尝试了一个catch函数,只是想了解错误情况,我的第二个函数依赖于第一个。因此,如果第一个功能失败,catch将返回错误,但如果第二个功能失败,我想使用相同的catch引发错误,则下面的代码不会发生这种情况,我可以实现此逻辑还是必须实现两个单独的try and catch?

main.js

try {

    //1st function 
    specialtyRefillsCache = await new CacheUtility().refillsCache(request.uniqueRxIds)
    const rxInfosArray = specialtyRefillsCache.map((rxInfo: any) => {
        return this.mapSpecialtyRequest(rxInfo);
    });
    if (rxInfosArray.length > 0) {
        const tokenID = request.body.tokenID;
        // 2nd function
        const specialtyMembersInfoCache =
            await new CacheUtility().MemberInfoCache(tokenID);
        this.rxInfos = rxInfosArray;
    }

} catch (e) {
    return this.errorHandler(request, 'no patient info for given HBS ID');
}

1 个答案:

答案 0 :(得分:0)

我希望能代表您的问题的简单案例

function f1(num){
    if(num > 6){
        return 10;
    } 
    else{
        throw new Error("Error from 1st function");
    }
}

function f2(){
   throw new Error("I am an error from 2nd function");
}

function junk(){
    try {
      var a=f1(7);
      if(a === 10){
         f2();
      }

     } catch(e){
         console.log(e);
     } 
}