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.
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
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
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); };
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(); } }