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①

瀏覽器相容性

另見