Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to ONLY handle a promise error?

See the example below, where method will return a promise and resolve/reject that promise accordingly. I'm not interested in handling it's resolve at this point, I just want to handle the reject.

Is there a better, cross browser way of doing it without declaring that useless success function?

  MyClass.method().then((sData) => {
    // Nothing to do here
  }, (eData) => {
    // Important code to run here
  })

In my code I'm using AngularJS promises. However the question is relevant for other common libraries and the native Promise object.

like image 762
caiocpricci2 Avatar asked Oct 27 '25 18:10

caiocpricci2


1 Answers

As the other answers state use the .catch function for this.

MyClass.method()
  .catch(error => { error handling logic (async)})

What I would like to add is the following:

Normally in the .then() function you provide 2 callbacks like this (these callbacks always will be executed asynchronous):

const promise2 = doSomething().then(successCallback, failureCallback);

However .catch() is shorthand for then() where the successCallback is filled in with null.

then(null, failureCallback)
like image 98
Willem van der Veen Avatar answered Oct 29 '25 08:10

Willem van der Veen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!