When communicating with some backend API, data travels over the network using the HTTP protocol. As such, failures may occur, be it on our own device (i.e. the browser) or on the server-side which may not be available or unable to process our request. We need to handle such error responses and give the user a proper feedback.
import { HttpErrorResponset } from '@angular/common/http'; export class AppComponent { people; message; constructor(private peopleService: PeopleService) {} fetchPeople() { this.peopleService .fetchPeople() .subscribe( (data) => { this.message = null; this.people = data; }, (err: HttpErrorResponse) => { if (err instanceof Error) { // client-side error this.message = `An error occured ${err.error.message}`; } else { this.message = `Backend returned error code ${err.status}, body was: ${err.message}`; } } ); } }