IDBTransaction:错误事件
当请求返回错误时,error
事件将在 IDBTransaction
上触发,并且该事件会冒泡到事务对象。
注意: 要处理事务失败的所有方式,请考虑改为侦听 abort
事件。
语法
在诸如 addEventListener()
之类的方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("error", (event) => {});
onerror = (event) => {};
事件类型
一个通用的 Event
。
冒泡
此事件冒泡到 IDBDatabase
。event.target
属性引用冒泡的 IDBTransaction
对象。
有关更多信息,请参阅 事件冒泡。
示例
此示例打开一个数据库并尝试添加记录,侦听 add()
操作的 error
事件(例如,如果具有给定 taskTitle
的记录已存在,则会发生这种情况)
js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// 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");
transaction.addEventListener("error", () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
});
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);
};
相同的示例,使用 onerror
属性而不是 addEventListener()
js
// Open the database
const dBOpenRequest = window.indexedDB.open("toDoList", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// 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");
transaction.onerror = () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
};
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);
};
浏览器兼容性
BCD 表仅在启用 JavaScript 的浏览器中加载。