【问题标题】:How to catch an error using try and catch for multiple functions?如何使用 try 和 catch 来捕获多个函数的错误?
【发布时间】:2019-01-03 18:02:44
【问题描述】:

我尝试了一个 catch 函数,只是想了解错误情况,我的第二个函数依赖于第一个函数。因此,如果第一个函数失败,catch 将返回错误,但如果第二个函数失败,我想使用相同的 catch 来抛出错误,下面的代码不会发生这种情况,我可以实现这个逻辑还是我必须实现两个单独的 try 和 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');
}

【问题讨论】:

  • 当“第二个函数失败”时你会抛出错误吗?
  • @quirimmo 是的,我有来自函数的错误,但问题是我如何返回给调用者,我是否需要为第二个函数添加另一个捕获?我想对第二个函数使用相同的错误处理程序

标签: javascript arrays angular try-catch


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多