传递给map的无效键请求,以获取值。处理这个异常

问题描述 投票:0回答:1

我有一张地图,我想找回一张。价值 基于 钥匙 以 "id "的形式传递。但在某些情况下,传递的 "id "是无效的,即它不存在于地图中,这反过来又使应用程序崩溃。抛出Error是否会导致这个问题?我试着用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个回答
0
投票

使用 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) 并不是一个好的测试,因为即使对象上存在属性,但却是falsey,比如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);
}
© www.soinside.com 2019 - 2024. All rights reserved.