angular - 使用异步/等待时,错误处理程序返回默认值

标签 angular typescript error-handling async-await angular7

Angular tutorial中提出了一个错误处理程序,该处理程序在发生错误的情况下可以将默认值返回给调用方。

/**
 * Handle Http operation that failed.
 * Let the app continue.
 * @param operation - name of the operation that failed
 * @param result - optional value to return as the observable result
 */
private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // TODO: better job of transforming error for user consumption
    this.log(`${operation} failed: ${error.message}`);

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

现在,我使用async/await进行了网络服务调用:

public async getItemsAsync() {
    try {
      return await this.http.get<string[]>("/some/url").toPromise();
    }
    catch (error) {
      this.handleError<string[]>('getItemsAsync', []);
    }
}

我必须更改什么才能能够从错误处理程序返回默认值?

private handleError<T>(operation = 'operation', result?: T) {  
    console.log(`${operation} failed: ${error.message}`);

    // let the app keep running by returning an empty result.
    return result as T;
}

我应该返回Observable还是Promise?我都尝试过,但是没有编译。目前,尚未返回string[]。我只得到undefined

最佳答案

考虑在可观察的级别上处理错误:

async getItemsAsync() {
    return await this.http
      .get<string[]>("/some/url")
      .pipe(catchError(this.handleError<string[]>("getItemsAsync", [])))
      .toPromise();
}

您可以使用RxJS中的catchError运算符。这将运行您的错误日志记录,并将您指定的值的可观察值返回给handleError函数。然后,您的toPromise运算符将可观察到的错误或api响应中的值转换为promise。

Stackblitz demo

关于angular - 使用异步/等待时,错误处理程序返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58690926/

相关文章:

angular - 在自定义 ErrorHandler 中注入(inject)服务会导致 "Cannot instantiate cyclic dependency!"错误,我该如何解决?

html - 如何将下拉菜单对齐到 mat-card-title 元素的右侧?

visual-studio - "typescript intellisense"在我的 Razor View 中?

python - 一般来说,我应该编写代码体的多个版本,以防用户丢失软件包吗?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

Angular 6 库组件和 SCSS

css - 不在页面顶部时隐藏工具栏组件

javascript - moment/moment-timezone 中是否有内置函数可以将时区名称转换为 "human readable format"?

TypeScript 无法通过通用引用对类型进行索引

r - 使用for回路和georoute计算行驶距离时跳过错误