Search code examples
angulartypescripterror-handlingasync-awaitangular7

Error handler returning default value, when using async/await


There is a proposed error handler in the Angular tutorial, which is able to return a default value to the caller in the case of an error.

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

Now I have a webservice call using async/await:

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

What do I have to change to be able to return a default value from my error handler?

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

Should I return an Observable or a Promise? I tried both, but it didn't compile. Currently, string[] isn't returned. I only get undefined.


Solution

  • Consider handling the error at the observable level:

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

    You can use the catchError operator from RxJS. This will run your error logging and and return an observable of the value you specify to the handleError function. Then your toPromise operator converts either the error observable or the value from your api response to a promise.

    Stackblitz demo