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

问题描述 投票:1回答:1

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

现在我有了使用异步/等待的网络服务呼叫:

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

angular typescript error-handling async-await angular7
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.