代码之家  ›  专栏  ›  技术社区  ›  Nils

typescript/angular try catch,try块中的任何错误都不会捕获块

  •  5
  • Nils  · 技术社区  · 7 年前

    我用的是斜角字体。 在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的“data”返回“null”, 但是掷球不会接住盖帽 此外,尝试不引发,它为“data”提供空错误…在这种情况下,也不会捕获块。

    1 回复  |  直到 7 年前
        1
  •  10
  •   user9315861    7 年前

    try/catch 不会在传递给的回调中捕获任何内容 subscribe (或) then ,或者 setTimeout 或者其他任何在不同的“勾选”或“微任务”上运行的工具。您必须在发生错误的任务中捕获错误。

    如果我理解错误发生时你在做什么,我可以建议更好的选择。如果您真正想做的就是记录它,那么您当然可以在检查完空值后立即这样做。

    您可以考虑在使用可观测数据之前对其进行映射,并在为空时对可观测数据发出错误,例如:

    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") (我想)。