IDBTransaction:error 事件
當請求返回錯誤並且事件冒泡到事務物件時,會在 IDBTransaction 上觸發 error 事件。
注意:要處理事務可能失敗的所有方式,請考慮監聽 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");
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
transaction.addEventListener("error", () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
});
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");
const objectStore = transaction.objectStore("toDoList");
const newItem = {
taskTitle: "my task",
hours: 10,
minutes: 10,
day: 10,
month: "January",
year: 2020,
};
transaction.onerror = () => {
console.log(`Error adding new item: ${newItem.taskTitle}`);
};
const objectStoreRequest = objectStore.add(newItem);
};
規範
| 規範 |
|---|
| Indexed Database API 3.0 # eventdef-idbrequest-error |
瀏覽器相容性
載入中…