Error handling

As we saw earlier, then takes two arguments, one for success, one for failure (or fulfill and reject, in promises-speak):

get('story.json')
.then(function(response) {
    console.log("Success!", response);
}, function(error) {
    console.log("Failed!", error);
});

.fail, .catch

Some librairies implement the method .fail (or .catch) which is equivalent to .then(undefined, func), for example:

get('story.json')
.then(function(response) {
    return JSON.parse(response);
})
.then(function(response) {
    console.log("Success!", response);
})
.fail(function(error) {
    console.log("Failed!", error);
});

Rejection order

The following codes are not equivalent:

get('story.json')
.then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.log("Failed!", error);
});

and

get('story.json')
.then(function(response) {
  console.log("Success!", response);
})
.fail(function(error) {
  console.log("Failed!", error);
});

The difference is subtle, but extremely useful. Promise rejections skip forward to the next then with a rejection callback (or fail, since it's equivalent). With then(func1, func2), func1 or func2 will be called, never both. But with then(func1).fail(func2), both will be called if func1 rejects, as they're separate steps in the chain.

Javascript Exceptions

Rejections happen when a promise is explicitly rejected, but also implicitly if an error is thrown in the constructor callback. Let's take a look at the previous example:

// Step1: get the json content
get('story.json')

// Step2: parse the json content
.then(function(response) {
    return JSON.parse(response);
})

// Step3: show the parsed results
.then(function(response) {
    console.log("Success!", response);
})

// Handle errors
.fail(function(error) {
    console.log("Failed!", error);
});

The Javascript method JSON.parse can throw an exception (SyntaxError) if the string is not valid JSON. This exception (if occurs) will be handled by the .fail.

Basically, the .then(func) is encapsulating the call to func with a try { func(resolved) } catch (e) { // return rejected promise }.

Last updated