Skip to content

Promise.catch()

David Fahlander edited this page Jun 11, 2014 · 8 revisions

Syntax

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"
});

Parameters

Return Value

The method will return another Promise that will resolve with the return value of given callback.

Description

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.

Samples

Catching Error Events

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

Catching Thrown Exceptions

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

Catching 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 (DOMError, function (e) {
    alert ("DOMError occurred: " + e);
}).catch (function (e) {
    alert ("Unknown error occurred: " + e);
});

Catching Error of Specific 'name'

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

See Also

Clone this wiki locally