Handling Asynchronous Exception with Bluebird Promises
When working with asynchronous routines, exception handling can be tricky to manage. Promises, a key feature of Bluebird.js, provide a structured way to handle asynchronous exceptions.
The Challenge
In your code example, a setTimeout is used in a non-promise callback. When an error is thrown within this callback, Bluebird's catch will not be triggered, causing the program to crash.
Bluebird's Promise Structure
Promises intercept exceptions thrown within their callback functions (then/catch/Promise constructor). To handle exceptions from asynchronous callbacks, it's crucial to wrap them in a promise.
Elegant Exception Handling
In your scenario, you can enclose the setTimeout callback in a promise. The catch block will then catch the error:
<code class="javascript">function getPromise() { return new Promise(function(resolve, reject) { setTimeout(resolve, 500); }).then(function() { console.log("hihihihi"); throw new Error("Oh no!"); }); }</code>
Rejection is Key
Never throw errors directly within non-promise callbacks. Instead, reject the surrounding promise. If necessary, use try-catch to ensure proper handling.
<code class="javascript">function getPromise() { return new Promise(function(resolve, reject) { try { setTimeout(resolve, 500); } catch (err) { reject(err); } }); }</code>
By adhering to these principles, you can ensure graceful exception handling in both Node.js and the browser, even for rogue asynchronous callbacks.
The above is the detailed content of How Can I Handle Asynchronous Exceptions with Bluebird Promises?. For more information, please follow other related articles on the PHP Chinese website!