[Angular] Handle HTTP Errors in Angular with HttpErrorResponse interface

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

 

    原文作者:Zhentiw
    原文地址: https://www.cnblogs.com/Answer1215/p/8448860.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞