[英]TypeScript/Angular try catch, any error in try block not going to catch block
我正在使用Angular和TypeScript。 在API調用的情況下,我使用了try catch構造來進行錯誤處理。 如果在try塊中發生任何錯誤,它就不會捕獲阻塞。 應用只在那里終止。
我也嘗試過使用throw
。 這是一個示例代碼段,
try {
this.api.getAPI(Id).subscribe( // this.api is my api service and getAPI is present there
(data: any) => {
if (data == null) {
throw 'Empty response';
}
},
(error: HttpErrorResponse) => {
console.log(error);
};
} catch(e) {
console.log(e);
}
在某些情況下,來自API的“數據”返回'null',但throw不會捕獲塊ALSO,嘗試不拋出,它為'data'提供null錯誤...在這種情況下也不會捕獲塊。
try/catch
不會捕獲傳遞給subscribe
(或者then
,或者setTimeout
或任何smiilar)的回調中的任何內容,這些回調在不同的“tick”或“microtask”上運行。 您必須在發生任務時捕獲錯誤。
如果我理解錯誤發生時你想要做什么,我可以建議更好的選擇。 如果您真正想要做的就是記錄它,那么當然可以在檢查null之后立即執行此操作。
您可以考慮在使用observable之前映射observable,並在null的情況下在observable上發出錯誤,例如:
const checkedData = this.api.getAPI(Id).pipe(map(data => {
if (data === null) return throwError("null data");
return data;
});
現在您可以訂閱
checkedData.subscribe(
data => /* do something with data */,
console.error
);
注意: throwError
是rxjs6。 對於rxjs5,它將return ErrorObservable("null data")
(我認為)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.