簡體   English   中英

如何從回調 function 中捕獲錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM