Asynchronous Exception Handling with Bluebird Promises
Consider the following scenario: you need to handle exceptions in a controlled environment without crashing the application. Let's examine this specific example using Bluebird promises:
<code class="javascript">var Promise = require('bluebird'); function getPromise(){ return new Promise(function(done, reject){ setTimeout(function(){ throw new Error("AJAJAJA"); }, 500); }); }</code>
When an exception is thrown within the setTimeout callback, it is captured by the Node.js event loop and logged to the console, causing the program to crash:
$ node bluebird.js c:\blp\rplus\bbcode\scratchboard\bluebird.js:6 throw new Error("AJAJAJA"); ^ Error: AJAJAJA at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Promises, however, can capture exceptions thrown from within their constructor callbacks. To handle exceptions thrown within asynchronous callbacks, you should wrap the callback with a promise that rejects upon errors.
<code class="javascript">function getPromise(){ return new Promise(function(done, reject){ setTimeout(function(){ done(); }, 500); }).then(function() { console.log("hihihihi"); throw new Error("Oh no!"); }); }</code>
In this modified example, the exception is caught by the surrounding promise chain:
$ node bluebird.js Error [Error: Oh no!]
Remember, promises do not catch exceptions from asynchronous callbacks. Always reject the surrounding promise in such cases, and use try-catch blocks if necessary. This approach ensures that exceptions are handled gracefully without crashing the application.
The above is the detailed content of How to Handle Exceptions in Asynchronous Callbacks with Bluebird Promises?. For more information, please follow other related articles on the PHP Chinese website!