IDBTransaction:error 属性

Baseline 广泛可用 *

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

* 此特性的某些部分可能存在不同级别的支持。

注意:此功能在 Web Workers 中可用。

IDBTransaction 接口的 IDBTransaction.error 属性会在事务不成功时返回错误类型。

返回一个包含相关错误的 DOMException,如果没有错误则返回 null

它可以引用引发它的请求对象的相同错误,也可以是事务失败(例如 QuotaExceededError)。

如果事务尚未完成,或者事务已完成但已成功提交,则此属性为 null

示例

在下面的代码片段中,我们打开了一个读/写事务,并在对象存储中添加了一些数据。另外,请注意事务事件处理函数中附加的函数,用于报告事务打开的成功或失败结果。请注意 transaction.onerror = (event) => { }; 块,它利用 transaction.error 来帮助报告事务不成功时出现的问题。有关完整的可运行示例,请参阅我们的 待办事项通知 应用(查看实时示例)。

js
const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = (event) => {
  note.appendChild(document.createElement("li")).textContent =
    "Database initialized.";

  // store the result of opening the database in the db variable.
  // This is used a lot below
  db = DBOpenRequest.result;

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  const newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction completed: database modification finished.";
  };

  transaction.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      `Transaction not opened due to error: ${transaction.error}`;
  };

  // create an object store on the transaction
  const objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  const objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.onsuccess)
    note.appendChild(document.createElement("li")).textContent =
      "Request successful.";
  };
}

规范

规范
Indexed Database API 3.0
# ref-for-dom-idbtransaction-error①

浏览器兼容性

另见