【问题标题】:Invalid-key request passed to a map to retrieve the value. Handle this exception传递给映射以检索值的无效键请求。处理这个异常
【发布时间】:2020-08-29 10:07:00
【问题描述】:

我有一张地图,并试图根据以“id”形式传递的 key 来检索 value。但是在某些情况下,传递的“id”是无效的,即它不存在于 Map 中,这反过来会导致应用程序崩溃。是否抛出错误导致此问题?我尝试使用 try-catch 进行试验,但它仍然继续出现故障,即屏幕在检测到此错误时停止加载。不确定我是否正确编写了 try-catch。在这种情况下,我该如何最好地处理这个问题,以阻止应用程序出现故障并继续加载屏幕。

失败的方法:

    this.hmItems = {};   //Map<Integer,Item>
    Address.prototype.getItem = function (id) {
            var item = this.hmItems[id];
            if (!item)
                throw new Error("'Illegal argument: id=" + id);
            return item;
    };

另一种失败的方法:

this.hmItems = {};   //Map<Integer,Item>
Address.prototype.getItem = function (id) {
   try {
       var item = this.hmItems[id];
       if (!item) throw "illegal id!!!!!!!!!";
       return item;
       } catch(err) {
       //log exception
   }
}

【问题讨论】:

    标签: javascript dictionary hashmap key-value


    【解决方案1】:

    使用hasOwnProperty查看hmItems对象上是否存在该属性:

    this.hmItems = {}; //Map<Integer,Item>
    Address.prototype.getItem = function(id) {
      if (!this.hmItems.hasOwnProperty(id)) {
        throw new Error("'Illegal argument: id=" + id);
      }
      return this.hmItems[id];
    };
    

    仅检查 var item = this.hmItems[id]; if (!item) 并不是一个好的测试,因为即使该属性存在于对象上但它是错误的,例如 0 或 null,它也会失败。

    现场演示:

    class Address {
      hmItems = {
        1: 10,
        2: 0
      };
      getItem(id) {
        if (!this.hmItems.hasOwnProperty(id)) {
          throw new Error("'Illegal argument: id=" + id);
        }
        return this.hmItems[id];
      }
    }
    
    const a = new Address();
    
    // Works:
    console.log(a.getItem(1));
    // Works:
    console.log(a.getItem(2));
    // Throws:
    try {
      console.log(a.getItem(3));
    } catch(e) {
      console.log(e.message);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 2022-09-28
      • 2017-05-17
      • 2016-08-08
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多