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}`);
};
};
规范
| 规范 |
|---|
| Indexed Database API 3.0 # eventdef-idbrequest-error |
浏览器兼容性
加载中…