liveBook · Manning

Error handling

As explained in Secrets of the JavaScript Ninja, Second Edition

The practice of detecting and responding to errors that occur during program execution.

Asynchronous callbacks can make errors hard to catch. A try-catch around a call that starts a task may not catch an error raised later, when the callback runs. Node.js-style callbacks commonly report failure through an `err` argument. section 6.3.1

try {
  getJSON("data/ninjas.json", function() {
    //Handle results
  });
} catch(e) {/*Handle errors*/}

Compare the surrounding try-catch with the callback’s later execution: the catch does not automatically handle errors from that asynchronous work. section 6.3.1

With chained promises, one catch can handle a failure from any earlier step. This keeps whole-sequence error handling out of each individual success step. section 6.3.5

Listing 6.16. Chaining promises with then
getJSON("data/ninjas.json")
 .then(ninjas => getJSON(ninjas[0].missionsUrl))                         #A
 .then(missions => getJSON(missions[0].detailsUrl))                      #A
 .then(mission => assert(mission !== null, "Ninja mission obtained!"))   #A
 .catch(error => fail("An error has occurred"));                         #B

The chain fetches ninja and mission data in sequence, then uses one catch for failures along the way. section 6.3.5

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Compares try-catch limits around callbacks with Node-style error arguments and catch handling across a promise chain.
Examples
Uses nested ninja-data callbacks and a chained sequence of mission requests.
What you can do after
Understand why asynchronous callback timing can bypass surrounding try-catch and how chained catch handles earlier promise failures.
How it connects
Connects callbacks, the event loop, try-catch, and promises.

Also explained in

Compare how 5 books explain error handling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.