您的位置:首页 > 理论基础 > 计算机网络

[Angular] Handle HTTP Errors in Angular with HttpErrorResponse interface

2018-02-14 20:46 471 查看
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}`;
}
}
);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐