From: Kai Moritz Date: Sat, 16 May 2020 10:49:37 +0000 (+0200) Subject: 6: Get Data from a Server X-Git-Url: https://juplo.de/gitweb/?p=examples%2Fangular-tour-of-heroes;a=commitdiff_plain;h=10071c9e2d5fefe91c5b8d9946bb964776b59c0e 6: Get Data from a Server e) Heroes and HTTP - Error handling --- diff --git a/src/app/hero.service.ts b/src/app/hero.service.ts index d44f22f..90fa42c 100644 --- a/src/app/hero.service.ts +++ b/src/app/hero.service.ts @@ -2,8 +2,9 @@ import { Injectable } from '@angular/core'; import { Observable, of, EMPTY } from 'rxjs'; import { Hero } from './hero'; import { HEROES } from './mock-heroes'; -import { HttpClient } from '@angular/common/http'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; import { MessageService } from './message.service'; +import { catchError } from 'rxjs/operators'; @Injectable({ @@ -19,7 +20,11 @@ export class HeroService { getHeroes(): Observable { this.log('fetching heroes...'); - return this.http.get(this.heroesUrl); + return this.http + .get(this.heroesUrl) + .pipe( + catchError(this.handleError('getHeroes', [])) + ); } getHero(id: number): Observable { @@ -32,6 +37,26 @@ export class HeroService { } } + /** + * 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(operation = 'operation', result?: T) { + return (error: any): Observable => { + + // 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); + }; + } + /** Log a HeroService message with the MessageService */ private log(message: string) { this.messageService.add(`HeroService: ${message}`);