[英]angular: catching errors in rxjs pipe/mergemap sequence
目前,我的代碼結構如下,並且效果很好:
// service:
getRequestA() { return this.http.get(someUrl) }
getRequestB(id) { return this.http.get(someUrl + id) }
getRequestC(id) { return this.http.get(someUrl + id) }
getAll() {
return getRequestA()
.pipe(
mergeMap((resp) => {
return this.getRequestB(resp.id)
}),
mergeMap((resp) => {
return this.getRequestC(resp.id)
})
)
}
這允許我在我的組件中執行此操作:
// component:
service.getAll().subscribe(resp => {
// result of service.getRequestC()
}, error => {
// error occurred in any 1 of the 3 http calls
});
這很好,因為我需要每個調用的結果才能觸發下一個調用,而我只關心最終的結果。 但是,現在我想知道3個http調用中哪個具體失敗,以便向用戶顯示更好的錯誤。 我已經嘗試了很多東西,但無法弄清楚在服務中拋出自定義錯誤,然后我可以在組件中區分。 在此先感謝您的任何建議!
像這樣的安排應該讓你標記並重新拋出任何錯誤:
const tagError = (tag, error) => {
error.tag = tag;
return error;
};
getAll() {
return getRequestA().pipe(
catchError(error => { throw tagError("A", error); }),
mergeMap(resp => this.getRequestB(resp.id).pipe(
catchError(error => { throw tagError("B", error); })
)),
mergeMap(resp => this.getRequestC(resp.id).pipe(
catchError(error => { throw tagError("C", error); })
))
);
}
實際上,您可以進一步將tagError
函數轉換為可管道運算符:
const tagError = tag => catchError(error => {
error.tag = tag;
throw error;
});
getAll() {
return getRequestA().pipe(
tagError("A"),
mergeMap(resp => this.getRequestB(resp.id).pipe(tagError("B"))),
mergeMap(resp => this.getRequestC(resp.id).pipe(tagError("C")))
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.