[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}`; } } ); } }
相关文章推荐
- How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
- [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests
- [Ramda] Handle Errors in Ramda Pipelines with tryCatch
- error: Couldn't start Appium REST http interface listener. Requested port is already in use. Please
- BEA-141150 - An error occurred while preparing application component uri of application application with HTTP response responseCode: message
- BEA-141150 - An error occurred while preparing application component uri of application application with HTTP response responseC
- Struggling trying to get cookie out of response with HttpClient in .net 4.5
- restangular: Differences with $resource 接上篇Something about http request in angularjs
- BEA-141150 - An error occurred while preparing application component uri of application application with HTTP response responseC
- angular.min.js:118 Error: [ng:areq] http://errors.angularjs.org/1.5.8/ng/areq?
- Access-Control-Allow-Origin: Dealing with CORS Errors in Angular
- 转:Working with HttpWebRequest and HttpWebResponse in ASP.NET
- [Angular] Set Metadata in HTTP Headers with Angular HttpHeaders
- angularjs Error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.8/ngRepeat/dupes?
- angular.min.js:118 Error: [ng:areq] http://errors.angularjs.org/1.5.8/ng/areq?
- [Angular] Fetch non-JSON data by specifying HttpClient responseType in Angular
- Error: [ng:areq] http://errors.angularjs.org...undefined
- angularjs报错汇总—— angularjs Error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.
- Error: [ng:areq] http://errors.AngularJS.org/1.5.8/ng/areq?p0=HelloCtrl&p1=not%20a%20function%2C%20g
- Error creating bean with name 'sqlMapClient' defined in ServletContext resource的可能原因