How to do it...

Let's perform the following steps to add error handling to our blog post service API:

  1. First, let's create an error handler in our /src/app/posts/blog-post.service.ts service. Since our error handler is for our promise-based HTTP requests, we will also make this handler return a promise object. This error handler will also parse out an error object from the API that we can inspect for details about our API failure:
...
private handleError(error: any): Promise<any> {
let errorJSON = JSON.parse(error._body).error;
console.error('An error occurred', errorJSON);
return Promise.reject(errorJSON || error);
}
...
  1. Next, let's add our new error handler function to our getBlogMetadata method. We'll also want to set our parameters option in our request to null so that it will not pass our API key through the request to simulate a forbidden error response from the API.
...
getBlogMetadata(): Promise<number> {
let params: URLSearchParams = new URLSearchParams();
params.set('key', environment.bloggerAPIKey);
return this.http.get(this.blogUrl, {params: null})
.toPromise()
.then((response) => {
return response.json();
})
.catch(this.handleError);
}
...
  1. Now, when errors happen in our API requests, we will get an error callback in our promise that we can use the catch callback of the promise standard to respond to. We can simply add a new postLoadError property to our component to hold any error results we get back. We will also be able to use this object as a flag to tell our template to display an error to the user.
...
private postLoadError: Object;
ngOnInit() {
let promises:Promise<any>[] = [];
promises.push(this.blogPostsService.getPosts());
promises.push(this.blogPostsService.getBlogMetadata());
Promise.all(promises).then(
(data) => {
this.posts = data[0];
this.metadata = data[1]
}
).catch(error => { this.postLoadError = error });
}
...
  1. Finally, let's add an error message to our /src/app/posts/post-list.component.html template. To make sure that this error is only shown to users when an error occurs, we will put it behind a ngIf directive and make sure that the More Posts button is only accessible when there is no error.
<span *ngIf="postLoadError; else loadMoreBlock">
<div class="alert alert-warning" role="alert">
<strong>{{postLoadError.code}} -</strong> {{postLoadError.message}}
</div>
</span>
<ng-template #loadMoreBlock>
<button class="btn btn-block btn-outline-primary" [disabled]="loadingPosts" (click)="loadMorePosts()">More Posts</button>
</ng-template>
  1. Now, when we view the /posts page, we will see an error displayed:
403 - Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.22.26