IDBRequest:error 事件
当错误导致请求失败时,将执行 error
处理程序。在 error
事件处理程序中,您可以访问请求的错误,以及对同一事务发出更多请求。
此事件不可取消,也不冒泡。
语法
在诸如 addEventListener()
之类的 方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("error", (event) => {});
onerror = (event) => {};
事件类型
一个通用的 Event
。
示例
此示例打开一个数据库并尝试添加一条记录,监听 add()
操作的 error
事件(例如,如果已经存在具有给定 taskTitle
的记录,则会发生这种情况)
js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.addEventListener("upgradeneeded", (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
});
DBOpenRequest.addEventListener("success", (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
const objectStoreRequest = objectStore.add(newItem);
objectStoreRequest.addEventListener("error", () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
});
});
同一个示例,使用 onerror
属性而不是 addEventListener()
js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
db.onerror = () => {
console.log("Error creating database");
};
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
DBOpenRequest.onsuccess = (event) => {
const db = DBOpenRequest.result;
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
const objectStoreRequest = objectStore.add(newItem);
objectStoreRequest.onerror = () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
};
};
浏览器兼容性
BCD 表仅在启用 JavaScript 的浏览器中加载。