-
-
Notifications
You must be signed in to change notification settings - Fork 669
Promise.catch()
David Fahlander edited this page Jun 11, 2014
·
8 revisions
promise.catch(function (error) {
// Handle error
});
promise.catch(ErrorType, function (error) {
// Handler error of ErrorType.
});
promise.catch("error-name-property", function (error) {
// Handler error where error.name === "error-name-property"
});
The method will return another Promise that will resolve with the return value of given callback.
Promise/A+ compliant catch() method. Enables caller to supply a callback to run if the promise fails. The return value of the catch callback will work as the resolve value for the returned promise.
This implementation also support to catch specific error types.
var db = new Dexie('db');
db.version(1).stores({friends: 'email,name'});
db.open();
// Un-remark following line to make it fail due to ConstraintError:
// db.friends.add({email: "abc@def.com", name: "Oliver"});
db.friends.add({email: "abc@def.com", name: "Gertrud"}).then(function() {
alert ("Successfully added friend into DB");
}).catch (function (e) {
alert ("Failed to add friend into DB: " + e);
});
var db = new Dexie('db');
db.version(1).stores({friends: 'email,name'});
db.open();
db.friends.add({email: "abc@def.com", name: "Gertrud"}).then(function() {
throw new Error ("Ha ha ha!");
}).catch (function (e) {
alert ("Failed: " + e.toString());
});
var db = new Dexie('db');
db.version(1).stores({friends: 'email,name'});
db.open();
// Un-remark following line to make it fail due to ConstraintError:
// db.friends.add({email: "abc@def.com", name: "Oliver"});
db.friends.add({email: "abc@def.com", name: "Gertrud"}).then(function() {
alert ("Successfully added friend into DB");
}).catch (DOMError, function (e) {
alert ("DOMError occurred: " + e);
}).catch (function (e) {
alert ("Unknown error occurred: " + e);
});
Sometimes the error type doesnt tell exactly what error occurred. IndexedDB for example, will always fail with a DOMError, where its name property tells the actual reason. Dexie.Promise has support for supplying a string as first argument. By doing that, the name property of the error is cheched against the given string.
var db = new Dexie('db');
db.version(1).stores({friends: 'email,name'});
db.open();
// Un-remark following line to make it fail due to ConstraintError:
// db.friends.add({email: "abc@def.com", name: "Oliver"});
db.friends.add({email: "abc@def.com", name: "Gertrud"}).then(function() {
alert ("Successfully added friend into DB");
}).catch ('ConstraintError', function (e) {
alert ("ConstraintError occurred: " + e);
}).catch (function (e) {
alert ("Unknown error occurred: " + e);
});
Dexie.js - minimalistic and bullet proof indexedDB library