Home > Article > Web Front-end > How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?
Asynchronous Exception Handling with Bluebird Promises
Q: How to handle unhandled exceptions in asynchronous callbacks with Bluebird promises?
Bluebird promises do not inherently catch exceptions thrown from asynchronous callbacks, unlike domains.
A: Use Promise Constructors or then() Closures to Handle Exceptions
To catch exceptions in async callbacks, wrap the callback in a promise constructor or then() closure:
<code class="javascript">function getPromise(){ return new Promise(function(done, reject){ setTimeout(function(){ throw new Error("AJAJAJA"); }, 500); }).then(function() { console.log("hihihihi"); throw new Error("Oh no!"); }); }</code>
Avoid Throwing in Custom Async Callbacks
Never throw exceptions directly in custom async callbacks (outside of promise callbacks). Instead, reject the surrounding promise:
<code class="javascript">function getPromise(){ return new Promise(function(done, reject){ setTimeout(done, 500); }).then(function() { console.log("hihihihi"); reject(new Error("Oh no!")); }); }</code>
Example
Using a promise constructor:
<code class="javascript">var p = getPromise(); p.then(function(){ console.log("Yay"); }).error(function(e){ console.log("Rejected",e); }).catch(Error, function(e){ console.log("Error",e); }).catch(function(e){ console.log("Unknown", e); });</code>
Output:
Error [Error: Oh no!]
This approach ensures that exceptions are caught and handled appropriately, preventing the application from crashing.
The above is the detailed content of How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?. For more information, please follow other related articles on the PHP Chinese website!