Home  >  Article  >  Web Front-end  >  How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?

How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?

DDD
DDDOriginal
2024-10-26 16:39:301058browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn