angularjs - Angular promises: trigger catch(...) from within a then(...) statement? -


is possible trigger catch(...) portion of promise chain within then(...) portion?

for example, make $http request , chain behavior. $http resolves successfully, upon processing of data, clear data more suited error case, want activate error handler instead.

the issue -- i've got promise chain being used within 2 locations; 1 within service itself, , other in controller activated service. controller 1 handles catch(...) portion of promise chain, opens modal displays error message.

so far, i've been able chain promise such that, whenever then(...) or catch(...) triggered within service, can return result, , triggered within controller -- expected.

but how have then(...) trigger within service, return result such catch(...) triggered instead within controller?

i tried using $q.reject(...) create , return new promise, return value within then(...) function, didn't seem work.

example:

var url = 'http://google.com'; $http.get(url).then(handlefirst).then(handlesecond).catch(error);  function handlefirst (response) {     console.log("handlefirstcalled", response);     return response; }  function handlesecond (response) {     console.log("handlesecondcalled", response);     return response; }  function error (response) {     console.log("errorcalled", response); } 

how handlefirst(...), skip executing handlesecond(...), , execute error(...) instead? note: can't call error(response) because there's no access outside promise chain.

[edit:] found solution, return $q.reject(response); work. however, service catch(...) function has return $q.reject(response). previously, had return response;, continued controller promise chain. controller activate then(...) within chain.

so return response; went:

service -> $http -> then(...) -> catch(...) -> controller -> (...)

by changing return $q.reject(response); goes:

service -> $http -> then(...) -> catch(...) -> controller -> catch (...)

you have 2 options in angular reject returned promise within then.

throw new error(...); // reject promise , trigger $exceptionhandler 

or:

return $q.reject(new error(...)); // reject promise 

use first 1 signal error can't recover , latter errors can recover from.

note in standard (es6 promises) , other compliant promises (like bluebird) distinction between throwing , rejecting isn't made.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -