简体   繁体   中英

Handling Errors early in the Promise Chain

I'm trying to find a general way to handle errors on promise chains. In the following snipped I'd like to handle an potential connection-error directly in my connection.js.

connection.js

function getData() {
  return fetch(myEndpoint)
   .catch(err => handleConnectionError(err)) // redirect to error page or similar
}

app.js

// import connection
connection.getData()
  .then(data => handleData(data.foo))

So there are two ways this scenario could play out:

  • If I catch the error in connection.js without throwing a new one, it will continue the promise chain and handleData() will fail
  • If I throw an Error again after handling it, the Promise chain wont be executed any further, but then I have an unhandled-promise-rejection error in the console.

So is there actually no better way, than catching and handling the errors everytime I'm using the getData() function somewhere in my app?

The best way to go about this would be to have a final catch to take care of all errors. EG:

function errorHandler(e) {
    if (e instanceof x) {
        //handle here
    }
}

And then:

fetch(endPoint).then(doSomething).then(doAnotherThing).catch(err => errorHandler(err))

If fetch or any other promise along the chain produces an error, the rest of the then() statements will be skipped and will be catched by the final catch function. From there you will need to make sure that all types of errors that could be thrown by all promises are taken care of.

However, you will need to get rid of the catch in getData as it will cause the rest of the chain to run as usual since the error is taken care of.

Hope that helps

So is there actually no better way, than catching and handling the errors everytime I'm using the getData() function somewhere in my app?

Yes, that's precisely what you should do:

function getData() {
  return fetch(myEndpoint)
}

// elsewhere:
connection.getData().then(handleData, handleConnectionError);

You usually don't know whether you always want to " redirect to error page or similar ". Maybe at some places in your app, you can handle connection errors by faking response data, and in other places you might want to show an error message instead of triggering a redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM