Indexeddb 简明教程
IndexedDB - Error Handling
我们编写的并非所有请求都会返回输出。这可能是由于 -
Not all requests we write will return an output. This may happen due to −
-
possible errors while writing the code.
-
If the storage limit has been exceeded.
-
If transactions have failed etc.
在失败的请求中,事务被取消,并且所有更改都被恢复。但有时我们希望在不恢复所有更改的情况下处理失败,为此可使用 request.onerror 处理程序。它可以通过调用 event.preventDefault() 来防止事务中止。
In a failed request the transaction is canceled, and all the changes are reverted. But sometimes we want to handle the failure without reverting all the changes to do that we use the request.onerror handler. It can prevent the transaction abort by calling event.preventDefault().
Example
以下给出了在 IndexedDB 中显示错误处理的一个示例:
An example to show error handling in IndexedDB is given below −
<!DOCTYPE html>
<html lang="en">
<head>
<title>IndexedDB</title>
</head>
<body>
<script>
const request = indexedDB.open("DATABASE", 1);
request.onsuccess = function (){
document.write("database creation success")
}
request.onerror = function(event){
document.write("Database not created " + event.target.errorCode);
}
</script>
</body>
</html>
Output
Database not created undefined
我们可以通过为此使用 db.onerror 处理程序来捕获错误。
We can catch errors using the db.onerror handler for it.
db.onerror = function(event) {
let request = event.target;
document.write("Error is found", request.error);
};
当具有相同 id 的对象已存在时,会发生约束错误。但有时,如果一个错误得到完全处理,并且我们不想报告该错误,则可以通过在 request.onerror 中使用 event.stopPropagation() 来阻止冒泡。
The constraint error is occured when an object with the same id already exists. But sometimes if any of an error is fully handled and we don’t want to report it we can stop the bubbling by using event.stopPropagation() in request.onerror.
request.onerror = function(event) {
if (request.error.name == "ConstraintError") {
document.write("id already exists");
event.preventDefault();
event.stopPropagation();
}
}