marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
2.99k stars 789 forks source link

Chapter 11 - Why try/catch is needed in the requestType function? #499

Closed alexpi closed 4 years ago

alexpi commented 4 years ago

In the requestType function we have:

function requestType(name, handler) {
  defineRequestType(name, (nest, content, source, callback) => {
    try {
      Promise.resolve(handler(nest, content, source))
        .then(response => callback(null, response),
              failure => callback(failure));
    } catch (exception) {
      callback(exception);
    }
  });
}

The text states that the call to handler had to be wrapped in a try block to make sure any exception it raises directly is given to the callback.

Since Promise.resolve converts the value returned by handler to a Promise, shouldn't the second argument to then() catch all exceptions?

marijnh commented 4 years ago

The call to handler() happens in the function itself, so when that throws, it'll raise a regular exception rather than creating a rejected promise.