[英]How can I catch errors from callback function
我有一個組件:
this.loginService.login(this.user, () => { this.router.navigateByUrl('/'); });
以及使用此方法的服務:
login(credentials, callback) { const headers = new HttpHeaders(credentials? { authorization: 'Basic ' + btoa(credentials.email + ':' + credentials.password) }: {}); this.http.get(this.API.crudAdmin + 'admin?email=' + credentials.email, { headers: headers }).subscribe(response => { if (response['name']) { this.authenticated = true; } else { this.authenticated = false; } return callback && callback(); }, error => { throw new Error('Error'); }); }
當我從組件調用登錄方法時,如何捕獲從登錄方法引發的錯誤?
在回調 function 中將錯誤作為第一個參數傳遞是一種常見模式。 所以你的登錄 function 看起來像:
login(credentuals, callback) {
this.http.get(options).subscribe((response) => {
// Logic, assuming it was successfuly, call callback with the first argument as null
callback(null)
}, (error) => {
// in the event of an error, pass error exception as the first argument
callback(error)
});
}
那么你可以在你的組件中處理這個:
this.loginService.login(credentials, (error) => {
if (error) {
// show error dialog, etc
} else {
this.router.navigateByUrl('/');
}
})
您可以將錯誤回調function 與成功回調一起傳遞。 當GET
請求失敗時將調用錯誤回調:
this.loginService.login(this.user,
() => this.router.navigateByUrl('/'),
//handle the error here, log to an error service etc.
(err) = > console.error(err)
);
在服務端,在Observable
的錯誤處理程序中,您調用從組件傳遞的errorCallback
:
login(credentials, successCallback, errorCallback) {
const headers = new HttpHeaders(credentials ? {
authorization: 'Basic ' + btoa(credentials.email + ':' + credentials.password)
} :
{});
this.http.get(this.API.crudAdmin + 'admin?email=' + credentials.email, {
headers: headers
}).subscribe(response => {
if (response['name']) {
this.authenticated = true;
} else {
this.authenticated = false;
}
successCallback && successCallback();
},
errorCallback);
}
傳統的 try-catch 在這里不起作用,因為這是一個異步操作,當GET
最終失敗時,catch 塊將無法捕獲錯誤。
這是因為loginService.login
方法會立即返回,而GET
請求是在后台異步發出的。 來自GET
的任何錯誤都不會被loginService.login
調用周圍的catch
塊處理。
您可以在 try/catch 塊中包圍您的 function 調用。
try {
this.loginService.login(this.user, () => {
this.router.navigateByUrl('/');
});
} catch (error) {
// do something with the thrown error
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.