I finally got Angular promise error handling down but it was counter-intuitive to me. I expected errors to be handled by the failure callback but instead I had to use a catch. <
The second argument should be almost never be used literally in application code while also using the first. It is mostly about promise library interoperability between different implementations.
You should always use .catch
unless you specifically have some weird corner case where you need .then(succcess, fail)
.
See The .then(success, fail) anti-pattern.
Also Q library (The one angular $q is based on) has similar section in their readme
By angularJS documentation for $q:
Methods
then(successCallback, errorCallback, notifyCallback) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available.
.....
catch(errorCallback) – shorthand for promise.then(null, errorCallback)
The two pieces of code you posted are identical.
I think you're slightly misunderstanding how promises work.
In your first code block there is only one promise object and it's SomeAsyncService.getData()
. The errorCallback is not called here because that promise is resolved.
In the second code block there are actually 2 promise objects you're working with. Note that .then()
"returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback". So what's happening is you're catching the error from the second promise returned from SomeAsyncService.getData().then(...)
.