简体   繁体   中英

How to catch an error using try and catch for multiple functions?

i have try an catch function just wanted to understand error scenario, my 2nd function is dependent on 1st. so if first function fails catch will return error but if second function fails i want to use same catch to throw error, its not happening with below code can i implement this logic or i have to implement two seprate 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');
}

simple case which I hope represents your problem

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);
     } 
}     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM