prismicio/javascript-kit — pull request #16 by rudyrigot (2014-02-05 04:07:53+00:00)
Title: If API call fails, possibility to provide an onError callback

The initial issue: it is very bad to throw errors from an asynchronous I/O callback in a webserver made with Node.js, because then Node's main thread doesn't know how to catch the error, and the webserver crashes. Actually, Node.js released a solution to that which is called "[domains](http://nodejs.org/api/domain.html)", and that they call both unstable and risky even if it was stable.

Throwing such an error is what the prismic.io kit does [right here](https://github.com/prismicio/javascript-kit/blob/master/src/api.js#L105), and that explains why sometimes, the express.js server in the starter kit would crash, and express.js's error handler seemed unable to do anything.

In summary, the problem lines of code in the kit are:
```javascript
h.get(options, function(response) { // we're in a I/O callback, errors are not caught anymore
if(response.statusCode && response.statusCode == 200) {
// Do what's to do if ok
} else {
throw new Error("Unexpected status code [" + response.statusCode + "]") // oops!
}
});
```

The solution: when calling the API, passing an "onError" callback that will execute in the event of an error, rather than the `throw` statement.

What this pull request contains:
* the "onReady" callback, which executes when the API call was a success, was sometimes called "onReady" and sometimes just "callback". Since we're adding another callback, and this could get ambiguous, they were all renamed "onReady".
* passing of the "onError" function, from the kit's endpoint, down to the request handlers.
* replacing the `throw` statement by a call of the `onError` function if the `onError` function is provided; or else, executing the `throw` statement anyway (is this a good idea? this means that if the user forgets to provide the `onError` function when they use the kit in a Node.js webserver, the server will crash on the next error)
* documenting the change (including this last part about how `onError` is needed in a Node.js server)
* the qunit that is already there doesn't work with Node.js, but with phantom.js. I tried including [grunt-node-qunit](https://npmjs.org/package/grunt-node-qunit), but it wouldn't work and is very badly documented. Eventually, I gave up, and just created a file you can launch with `node test/nodetest.js` for now, and [an issue to make it better later](#15).