Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return success when handling error in a promise

I have a promise that handles a HTTP request performed over a Web API:

promise = promise.then(r => { 
    // ...
  }, error => {
    if (error.status == 404) {
      // Here I can fix an error and continue properly
    } else {
      // Here the error should be propagated further in the promise
    }
}

// later in the code:
promise.catch(r => { /* More error handling */ } );

Later in the code this promise is chained to more error checks.

In case of a 404 error, I can actually "fix" a problem, and I don't want the other handler to trigger. I'd rather want to make the promise a success in this case. How can I do that?


A bit more code to explain my case more deeply:

refresh() {
  this.refreshAsync().catch(r => {
     // Show error to the user.
     notifications.showError("Unexpected error happened");
  });
}

async refreshAsync() {
  // Here goes a lot of vue-resource calls to gather the necessary data for a view. They are chained with `await`. Only one of them:
  await this.$http.get(url).then(r => {
    this.data = r.data;
  }, error => {
    // 404 is actually a legit response for API to return, so the user notification above should not be shown
    if (error.status == 404) {
      // handle successfully
    } else {
      // propagate an error, so the handler above could show a warning to the user.
    }

  });

}
like image 269
Archeg Avatar asked Oct 16 '18 08:10

Archeg


People also ask

How do you handle errors in promises?

Error handling with promises 1 Implicit try…catch. The code of a promise executor and promise handlers has an "invisible try..catch " around it. ... 2 Rethrowing. As we already noticed, .catch at the end of the chain is similar to try..catch. ... 3 Unhandled rejections. What happens when an error is not handled? ... 4 Summary. ...

What happens when a promise gets stuck in JavaScript?

In case of an error, the promise becomes rejected, and the execution should jump to the closest rejection handler. But there is none. So the error gets “stuck”. There’s no code to handle it.

What happens if a promise fails to execute?

If any of the promises reject or execute to fail due to an error, all other promise results will be ignored. Let's create three promises to get information about three Pokémons.

How do I catch an exception outside of a promise?

When you raise an exception outside the promise, you must catch it with try/catch: try{ getUserById('a') .then(user=>console.log(user.username)) .catch(err=>console.log(`Caught by .catch ${error}`)); } catch(error) { console.log(`Caught by try/catch ${error}`); } Code language:JavaScript(javascript) Output:


1 Answers

You can simply return a reject/resolve

if(error.status == 404)
    return Promise.resolve('OK')
else
    return Promise.reject('fail')

I made an example showing how this work, just for this case:

httpRequest = function () {
  return new Promise(function (res, rej) {
    let status = (Math.round(Math.random()) === 1) ? 200 : 404;
    console.log(status)
    if (status === 200)
        return res({ status })
    else
        return rej({ status })
  })
}

let promise =
httpRequest()
    .then(res => Promise.resolve('success'))
    .catch(e => {
        if (e.status === 404)
            return Promise.resolve('success')
        else
            return Promise.reject('failed')
    })

promise
.then(res => {
    console.log(res)
})
.catch(e => {
    console.log('this should not happen')
})
like image 170
Timothy Lee Avatar answered Nov 11 '22 00:11

Timothy Lee