使用 async/await 时返回默认值的错误处理程序

Error handler returning default value, when using async/await

Angular tutorial 中提出了一个错误处理程序,它能够 return 在发生错误的情况下向调用方提供默认值。

/**
 * 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', []);
    }
}

我必须更改什么才能return 我的错误处理程序的默认值?

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;
}

我应该 return Observable 还是 Promise?我都试过了,但它没有编译。目前,string[] 未被 return 编辑。我只得到 undefined.

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

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

您可以使用 RxJS 中的 catchError 运算符。这将 运行 您的错误记录和 return 您指定给 handleError 函数的值的可观察值。然后您的 toPromise 运算符将可观察到的错误或您的 api 响应中的值转换为承诺。

Stackblitz demo