【问题标题】:TypeScript/Angular try catch, any error in try block not going to catch blockTypeScript/Angular try catch,try 块中的任何错误都不会捕获块
【发布时间】:2018-05-23 13:51:30
【问题描述】:

我正在使用 Angular 和 TypeScript。 在 API 调用的情况下,我使用 try catch 构造进行错误处理。 如果 try 块中发生任何错误,它根本不会捕获块。 应用程序仅在此处终止。

我也尝试过使用throw。 这是一个示例代码sn-p,

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 的“数据”返回“空”, 但 throw 不会抓住块 另外,尝试不抛出,它为“数据”给出空错误......在这种情况下也不会捕获块。

【问题讨论】:

    标签: javascript rxjs


    【解决方案1】:

    try/catch 不会在传递给subscribe(或then,或setTimeout 或任何类似的东西)的回调中捕获任何在不同“tick”或“微任务”上运行的东西。您必须在发生错误的任务中捕获错误。

    如果我了解您在发生错误时尝试执行的操作,我可以提出更好的替代方案。如果您真正想做的只是记录它,您当然可以在检查 null 之后立即执行此操作。

    您可以考虑在使用 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")(我认为)。

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 2014-03-04
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多