Tengo este escenario:
methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); }); } someMethod(): ng:IPromise<void> { const deferred = this.$q.defer<void>(); return this.OtherService.otherMethod() .catch ( e => { deferred.reject(reason); } } otherMethod(): ng.IPromise<any> { return this.HttpService.get(url); }Prueba:
¿Por qué, en el controlador.ts, se ejecuta el bloque entonces ?
El catch se ejecuta si algún then anterior (o catch ) arroja un error . Si no hay errores then el código ejecutará la siguiente declaración.
Así que tienes este código:
methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); // No errors thrown, so the code will continue in the next then }); } Entonces puedes arrojar un error dentro del catch . El código continuará con la captura siguiente:
methodA(): void { myServive.someMethod() .then( () => console.log("then") ) .catch( e => { console.log("catch"); throw new Error(e) // Some error happened! The code will continue in the next catch }); }¿Por qué, en el controlador.ts, se ejecuta el bloque entonces?
porque detectó el error y devolvió indefinido en service.ts
Parece que deberías deshacerte de catch/defer por completo en service.ts si no planeas manejar ningún error allí.
EDITAR: si desea que la captura se maneje en el controlador, simplemente elimine todas las cosas de service.ts y simplemente déjelo hacer:
// service.ts someMethod(): ng:IPromise<void> { return this.OtherService.otherMethod() } Si desea manejar la captura en service.ts Y en el controlador, vuelva a generar el error (o uno nuevo):
// service.ts someMethod(): ng:IPromise<void> { const deferred = this.$q.defer<void>(); return this.OtherService.otherMethod() .catch ( e => { // you can either do: // throw e // which rethrows the same error (same as not having a catch in here at all) // or you can handle the error and throw a new one like: // // ...some error handling code // throw new Error('my new error'); }); }No importa cuál elija, no necesita un diferido.