我有這樣的情景:
controller.ts
methodA()。void {
myServive.someMethod()
.then( () => console.log("then") )
.catch( e => {
console.log("catch"/span>)。
});
}
service.ts
someMethod()。ng:IPromise<void> {
const deferred = this.$q.defer<void> ()。
return this.OtherService.otherMethod()。
.catch ( e => {
deferred.reject(原因)。
}
otherservice.ts
otherMethod(): ng.IPromise< any> {
return this.HttpService.get(url)。
}
測驗:
- otherMethod (otherService.ts)從HttpService那里得到一個錯誤。
- someMethod (service.ts)中的catch已經被執行。
為什么在controller.ts中,then塊已被執行?
uj5u.com熱心網友回復:
catch被執行如果之前的then(或catch)拋出一個錯誤。如果沒有錯誤,代碼將執行下一個then陳述句。
所以你有這樣的代碼:
methodA()。void {
myServive.someMethod()
.then( () => console.log("then") )
.catch( e => {
console.log("catch"); //沒有拋出錯誤,所以代碼將繼續在下一個然后。
});
}
所以你可以在catch里面拋出一個錯誤。代碼將繼續到下一個catch中:
methodA()。void {
myServive.someMethod()
.then( () => console.log("then") )
.catch( e => {
console.log("catch"/span>)。
throw new Error(e) // Some error happened! 代碼將在下一個catch中繼續。
});
uj5u.com熱心網友回復:
為什么在controller.ts中,then塊被執行了呢?
因為你在service.ts
如果你不打算在service.ts中處理任何錯誤,看起來你應該在service.ts中完全去掉catch/defer。
編輯:如果你想在控制器中處理catch,那么就從service.ts中洗掉所有的東西,只讓做:
// service.ts
someMethod()。ng:IPromise<void> {
return this.OtherService.otherMethod()
}
如果你想在service.ts和控制器中處理catch,那么重新拋出錯誤(或一個新的錯誤):
// service.ts
someMethod()。ng:IPromise<void> {
const deferred = this.$q.defer<void> ()。
return this.OtherService.otherMethod()。
.catch ( e => {
//你可以這樣做:
//拋出e
///會重新拋出同樣的錯誤(和在這里沒有catch一樣)
//或者你可以處理這個錯誤并拋出一個新的錯誤,比如:
//
//...一些錯誤處理代碼。
///拋出新的錯誤('我的新錯誤');
});
無論你選擇哪一種,你都不需要遞延。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/307475.html
標籤:
