This is actually the second part of my previous article. And here is our Angular Novice to Ninja Roadmap.
- Introduction And Setting Up The Environment - Part One
- Typescript in Nutshell - Part Two
- Building Blocks of Angular - Part Three
- Binding Variations and Displaying Data - Part Four
- Building Reusable Components - Part Five
- Directives - Part Six
- Template Driven Forms in Angular - Part Seven
- Reactive Forms in Angular - Part Eight
- CRUD Operations with Fake Http Service in Angular - Part Nine
So far in the implementation, we assume that the call to the server always succeeds but in reality that’s not the case.
So here in ngOnInit(), we’re calling getPosts() method of our services. Let me simulate the scenario where the call to the server fails. So back in posts service let’s change the url to invalid url. Now let’s see what happens in the browser. Now back in the browser, the list of posts is not appearing.

But the user looking at this page? They have no clue what is going on under the hood. So we need to change our implementation and handle errors and give proper error messages to our user.
When it comes to handling errors, we have 2 types of errors.
- Unexpected
- Server is offline
Client sends the request to the server but server is not up and running to respond. - Network is down
So the server is online but the client cannot reach it. So as we’ve changed the url and make it invalid, we simulated this scenario. We could not reach the destination. - Unhandled Exceptions
When we have an unhandled exception in our API, the server is up and running, the network is fine, we call the server but because of a bug the request fails and results in unhandled exception.
- Server is offline
- Expected
Generally speaking there are 2 types of expected errors that we need to handle in our implementation.
- Not Found (404)
What are these errors? Imagine there are 2 users looking at the same page at the same time, User A deletes a post but that post is still visible on the User B screen. So if User B tries to delete that post, the server responds with the Not Found message. And in http protocol, it responds with the status code 404. Whenever we want to get the object from the server or update or delete it is possible that API endpoint will respond with 404. - Bad Request (400)
Imagine we’re building a signup form. Here we need to put the username, password and a few other fields as well. When we call the server to create the new account, it is possible that we have an account with the same username. So in that case, the server may respond with an error message which we call the bad request. And the status code in http protocol is 400.
So the server should tell the user that -- hey there is an account with the same username.
Handling Unexpected Errors
Now let’s see how to handle unexpected errors. So here in posts component in ngOnInit(), look at the subscribe method. Here we’ve passed the function working with response
- ngOnInit() {
- this.service.getPosts()
- .subscribe(response => {
- this.posts = response.json();
- });
- }
Now this subscribe() has another optional parameter.
Look here we have error parameter which is optional and here we need to pass the function that takes the error parameter and returns void. So here we pass once again an arrow function.
- ngOnInit() {
- this.service.getPosts()
- .subscribe(response => {
- this.posts = response.json();
- }, error => {
- alert('An Unexpected Error Occured.');
- });
- }
Now in a real world application, it is better to use Toast Notification instead of native alert function in javascript. These toast notifications are more user friendly. In case you don’t know what we mean by toast notification, think of the notification we get on facebook which is just the popup on the top right corner of the screen. It doesn’t freeze the browser, and automatically disappears after 5 seconds. And also the user can immediately close that. Also in the real world application, when the unexpected error occurred we want to log the error.
So now don’t worry about how to log the errors but to simulate this scenario, let’s write the errors on the console. And it is just for demonstration.
- ngOnInit() {
- this.service.getPosts()
- .subscribe(response => {
- this.posts = response.json();
- }, error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
So instead of logging the error on the console, we need to store it somewhere in a database on the server. One more thing, always use the best approach to write the code which increases the readability and understandability of your code. So here is our final code.
- export class PostsComponent implements OnInit {
- posts: any[];
- constructor(private service:PostService) {
- }
- ngOnInit() {
- this.service.getPosts()
- .subscribe(
- response => {
- this.posts = response.json();
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
- createPost(input: HTMLInputElement) {
- let post = { title: input.value };
- input.value = '';
- this.service.createPost(post)
- .subscribe(
- response => {
- post['id'] = response.json().id;
- this.posts.splice(0, 0, post);
- console.log(response.json());
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
- updatePost(post) {
- this.service.updatePost(post)
- .subscribe(
- response => {
- console.log(response.json());
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
- deletePost(post) {
- this.service.deletePost(post.id)
- .subscribe(
- response => {
- let index = this.posts.indexOf(post);
- this.posts.splice(index, 1);
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
- }
Now let’s implement this error alert in all the cases. And run the application and see the results with invalid url.
- private url = 'https://avjsonplaceholder.typicode.com/posts';
And if you run the application, you’ll see the alert in output.
Handling Expected Errors
Now let’s see how to handle expected errors. So here in deletePost(), we know that it is possible that the post with given id doesn’t exist on the server. So our API endpoint is going to return 404 message. If that’s the case we want to tell the user that this post has already been deleted.
So here (deletePost()) in error handler, we need to check the status of the response. As we already know that error parameter is of any type. So we need to use type innotations to work them perfectly. And to simulate the error, let’s provide the invalid id.
- deletePost(post) {
- // this.service.deletePost(post.id)
- // invalid id
- this.service.deletePost(345)
- .subscribe(
- response => {
- let index = this.posts.indexOf(post);
- this.posts.splice(index, 1);
- },
- // When we're working with arrow functions we always need to put
- // parameters in brackets if we more than 1 parameter or when we're using
- // type annotation inside.
- (error: Response) => {
- if(error.status === 404)
- alert('This Post Is Already Been Deleted');
- else {
- // We wanna display generic error message and log the error
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }
Because this fake service (JsonPlaceHolder) has only 100 posts and the id of last posts is 100, so run the application and see the result.
Now let’s take a look at another example. So here we go on createPost() method.
- createPost(input: HTMLInputElement) {
- let post = { title: input.value };
- input.value = '';
- this.service.createPost(post)
- .subscribe(
- response => {
- post['id'] = response.json().id;
- this.posts.splice(0, 0, post);
- console.log(response.json());
- },
- (error: Response) => {
- if(error.status === 400) {
- // now let's imagine the general alert message. Let's image we've a form
- // And in Reactive form article, we see how form object works in applicaton.
- // if it exists.
- this.form.setErrors(error.json()); // We know that it will not compile here.
- }
- else {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }
- deletePost(post) {
- this.service.deletePost(post.id)
- .subscribe(
- response => {
- let index = this.posts.indexOf(post);
- this.posts.splice(index, 1);
- },
- (error: Response) => {
- if(error.status === 404)
- alert('This Post Is Already Been Deleted');
- else {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }
So this is how we handle expected and non expected errors in the application.
Throwing Application Specific Errors
Still here is the problem in code (deletePost() in component). It is violating the principal of SoC.
- (error: Response) => {
- if(error.status === 404)
Earlier we created a service to encapsulate all the details about consuming http services on our backend. We introduced the service to hide all the complexity of our component. But in the above code, we’re looking at the response object on the server and we also checking the status of the response. This is not the language of our component, this is the language of our service. So we should change this implementation and move this logic inside our service. And here in the component, instead of working with Response object we need to work with an object that is part of our application domain, something that is not specific to http protocol. So let’s see how can we change the implementation.
So let’s go back to our posts service, here in deletePost() method there is an error or some kind of exception and I want to catch the error. And instead of sending the response object to our component, I want to send a different kind of object. An object that is part of our application domain. So first let’s see how can we catch the error.
- deletePost(id) {
- return this.http.delete(this.url + '/' + id);
- }
As we know that http methods return observable. Observable is a type that is part of a 3rd party library called Reactive extensions. And this type has a bunch of useful methods that we call operators. But these operators are not there by default,
Look here we’ve some methods in Observable. But here we need catch/catchError method or I would say catch/catchError operator. Actually these operators are the part of rxjs library of Angular.
Now you might think what is Rxjs?
It is an API or library for asynchronous programming where we use observable objects.
In every front end application, we make the connection through API to communicate the front end with backend. And in this communication we use http client. In Angular, we’ve built-in http protocol. And we just simply import it and use it in our application. HttpClient and many other modules use the library RxJS. RxJS library has the speciality that it has Observable. And we already discussed Observable in our previous article in detail. RxJS itself a simple library like jquery and RxJS helps a lot in asynchronous operations. Asynchronous means multiple tasks at a time. So with the help of asynchronous, our code executes without any blockage.
Asynchronous Programming is a very special thing in Javascript and initially we deal it with simple callbacks like we mostly do in jquery.
- $("button").click(function(){
- $("p").hide("slow", function(){
- alert("The paragraph is now hidden");
- });
- });
- $("button").click(function(){
- $("p").hide(1000);
- alert("The paragraph is now hidden");
- });
Look at this code, when the control executes the first statement which is the click event of button containing callback function. Until the callback function executes successfully, our next jquery statement will never be executed. This is how we’re implementing asynchronous programming here. But the problem with this approach is when we’re working with jquery, our single html element can contain many callback functions on different events and effects. This is how it contains a lot of nesting in the code. This is what we say callback hell.
Then Promise comes into the picture to solve this problem. It works the same as we’re working with callbacks. When we call the function it returns the promise object and it becomes resolved when function successfully complete otherwise it rejects.
- getPromise()
- .then(getPosts)
- .then(getCourses);
Here we use then() function to call the function. And it makes our code a lot simpler and we implement functional programming in which we just make the functions of different tasks and call it in then(). This is how we write the code in just one single statement instead of nesting our code.
We’ve already discussed the story of Observable. But you might wonder what the difference between Promise and Observable is? Where we use Promise and where we use Observable, you can get the idea from here.
RxJS Operator
Actually RxJS code of implementation varies. At this time, Angular 6 has been released. Normally, we install everything through npm and don’t specify its version to install. So everytime we install the latest version of different packages.
Open the command prompt and run this statement.
ng --version
Here we can see Angular 6 and RxJS 6.1.0 is installed in our machine.
RxJs contains different operators. Be aware, the way of implementation of these operators vary from version to version. Operators are nothing just like functions. Mostly operators operate on Observable object and return the Observable object. This is how we can chain the different operators with http request. So here we want to use the catch operator to handle the exception. The syntax of RxJS 6.1.0 is,
- import { nameOfOperatorsCommaSeparatedIfMultiple } from "rxjs/operators";
So this is the syntax of utilizing the operators in any typescript file. And if we want to use the Observable object in the file:
- import { Observable } from "rxjs";
So obviously when we’re working with Operators we definitely work with Observable. So both these import statements are essential. In RxJS 6.1.0, catch operator replaces with catchError. And when we use operators, we’ll use pipe in 6.1 version. So we were working with deletePost() method,
- deletePost(id) {
- return this.http.delete(this.url + '/' + id)
- .pipe(
- map(res => res),
- catchError((error: HttpErrorResponse) => {
- return Observable.throw();
- }));
- }
Look pipe is nothing but when we combine the functions. That’s why map and catchError operators have commas inside. We’re not making a chain like we do in jquery, we’re combining them here in pipe. And this pipe returns the Observable object of Response. And if you want to get an idea of map operator then you should take a look on this stackoverflow question. Map operator just transforms the result of one form to another form. Here in RxJS 6.1.0 version, catchError takes the argument of HttpErrorResponse rather than simple Response type. So we need the import statement here as well.
- import { HttpClient, HttpErrorResponse } from '@angular/common/http';
One more thing and let me be clear -- repeating each operator returns Observable object. So in the body of catchError, we’re returning Observable instead of void or any other type. Here we need to return an Observable that has an error so the consumer of this service (which in this case is component) will get that error and do something with that error. And to return the Observable, obviously we need to define the Observable in import statement.
- import { Observable, throwError } from "rxjs";
Here is our catchError method,
- catchError((error: HttpErrorResponse) => {
- return throwError();
- }))
This throwError() method returns a new Observable that has an error. Now what is the type of that error? The type of that error should be something specific to our application, not the Response object. So we need to create a new class to represent application specific errors.
To define application specific errors, define the typescript class in app/common folder with (app-error.ts) and here we define the class AppError.
- export class AppError {
- }
With the help of this class, we’ll represent the application error. Now here is the catchError() method, we define AppError() object inside throw() function
- catchError((error: HttpErrorResponse) => {
- return throwError(new AppError());
- }));
Now the good practice to include original error inside this AppError because somewhere we're going to get that error and log it on the server. So,
- export class AppError {
- constructor(public error: any) {}
- }
And here is the component deletePost() method.
- deletePost(id) {
- return this.http.delete(this.url + '/' + id)
- .pipe(
- map(res => res),
- catchError((error: HttpErrorResponse) => {
- return throwError(new AppError(error));
- }));
- }
So what we’re doing here, we’re catching the error object which is an instance of HttpErrorResponse class and then we’re returning a different kind of error that is specific to our application. Now we need to change this implementation and check for the status of the error if it is 404 or 400, we want to return a different kind of error because in our component we need to know if that post exists or not. And we don’t want to check this status of the response object. So go back in the common folder, and create a new class (not-found-error.ts)
- export class NotFoundError {
- }
Now we want to derive this class from AppError because this is kind of an application error but it is more specific. So,
- import { AppError } from './app-error';
- export class NotFoundError extends AppError {
- }
Now back in our service, we can check the status of the error.
- deletePost(id) {
- return this.http.delete(this.url + '/' + id)
- .pipe(
- map(res => res),
- catchError((error: HttpErrorResponse) => {
- if (error.status === 404)
- return throwError(new NotFoundError(error.json()));
- return throwError(new AppError(error.json()));
- }));
- }
Now in this case, we don’t want to put the original error here because we don’t want to log this error on the server. And as the argument of the constructor of NotFoundError is, I want to include an error object came from the server because the error object includes data about the invalid fields. So,
- return throwError(new NotFoundError(error.json()));
One last thing is, back in the component instead of working with Response object here in subscribe method,
- (error: Response) => {}
We’re going to work with AppError or one of its derivatives because in posts service, we are throwing AppError or NotFoundError. And since NotFoundError is a kind of AppError, we can say that essentially here we’re catching the response object and throwing an AppError object.
Here is our deletePost() component method,
- deletePost(post) {
- this.service.deletePost(post.id)
- .subscribe(
- response => {
- let index = this.posts.indexOf(post);
- this.posts.splice(index, 1);
- },
- (error: AppError) => {
- if(error instanceof NotFoundError)
- alert('This Post Is Already Been Deleted');
- else {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }
Now let’s implement BadRequest error message for createPost() as well. So here is the BadRequest class.
- import { AppError } from './app-error';
- export class BadRequest extends AppError {
- }
Now come on to the Post Service.
- import { BadRequest } from './../common/bad-request';
- import { NotFoundError } from './../common/not-found-error';
- import { AppError } from './../common/app-error';
- import { Http } from '@angular/http';
- import { Injectable } from '@angular/core';
- import { Observable, throwError } from "rxjs";
- import { catchError, map } from "rxjs/operators";
- import { HttpClient, HttpErrorResponse } from '@angular/common/http';
- @Injectable({
- providedIn: 'root'
- })
- export class PostService {
- private url = 'https://jsonplaceholder.typicode.com/posts';
- constructor(private http: Http) { }
- deletePost(id) {
- return this.http.delete(this.url + '/' + id)
- .pipe(
- map(res => res),
- catchError((error: HttpErrorResponse) => {
- if (error.status === 404)
- return throwError(new NotFoundError(error));
- return throwError(new AppError(error));
- }));
- }
- getPosts() {
- return this.http.get(this.url);
- }
- createPost(post) {
- return this.http.post(this.url, JSON.stringify(post))
- .pipe(
- map(res => res),
- catchError((error: HttpErrorResponse) => {
- if(error.status === 400)
- return throwError(new BadRequest(error));
- return throwError(new AppError(error));
- })
- )
- }
- updatePost(post){
- return this.http.patch(this.url + '/' + post.id, JSON.stringify({ isRead: true }))
- }
- }
And now come back again to post component.
- import { BadRequest } from './../common/bad-request';
- import { NotFoundError } from './../common/not-found-error';
- import { AppError } from './../common/app-error';
- import { PostService } from './../services/post.service';
- import { Component, OnInit } from '@angular/core';
- @Component({
- selector: 'app-posts',
- templateUrl: './posts.component.html',
- styleUrls: ['./posts.component.css']
- })
- export class PostsComponent implements OnInit {
- posts: any[];
- constructor(private service:PostService) {
- }
- ngOnInit() {
- this.service.getPosts()
- .subscribe(
- response => {
- this.posts = response.json();
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
- createPost(input: HTMLInputElement) {
- let post = { title: input.value };
- input.value = '';
- this.service.createPost(post)
- .subscribe(
- response => {
- post['id'] = response.json().id;
- this.posts.splice(0, 0, post);
- console.log(response.json());
- },
- (error: AppError) => {
- if(error instanceof BadRequest) {
- // this.form.setErrors(error.originalError);
- }
- else {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }
- updatePost(post) {
- this.service.updatePost(post)
- .subscribe(
- response => {
- console.log(response.json());
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
- deletePost(post) {
- this.service.deletePost(post.id)
- .subscribe(
- response => {
- let index = this.posts.indexOf(post);
- this.posts.splice(index, 1);
- },
- (error: AppError) => {
- if(error instanceof NotFoundError)
- alert('This Post Is Already Been Deleted');
- else {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }
- }
Now let’s test the application up to this point. So here in our post component in deletePost() send the invalid post id
this.service.deletePost(345)
And now we’re expecting to see the NotFoundError alert. So let’s try this,
And it is working successfully.
- import { Observable, throwError } from "rxjs";
This is the important statement, we define throwError operator here in rxjs with Observable.
Global Error Handling
Now let’s come back again to posts component, and if we see on the different methods of this component we’re repeating these 2 lines again and again in each method. These 2 lines are especially for handling unexpected errors. And now here we’re working with 1 component. In real world applications, we’ll work with 100s of components. And we don’t want to repeat these lines again and again.
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
When you watch some code that is repeating again and again in different places. It means that something is not right here. We need to refactor the code and make it better. So let’s see how to handle unexpected errors globally.
Once again add a new file in common folder (app-error-handler.ts). And here we want to export the class that is responsible for handling all the unexpected exceptions in our application. And now come to the angular website and search for errorhandler. This is one of the built-in classes in Angular. Now if you look at the implementation of this class, we can see here we have the method called handleError()
This method takes an error parameter of any type and returns void. And in the default implementation of this class in Angular, Angular simply logs this error message in the console. Now we want to provide a different implementation of this class. And in our implementation we’ll display an error message to the user and potentially log this error on the server. And here is an example of how to implement this class in our code.
So now let’s write the code in our application. And cut these 2 repetitive lines and put them into our global error handler.
- import { ErrorHandler } from "@angular/core";
- export class AppErrorHandler implements ErrorHandler {
- handleError(error) {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- }
But it is not so simple, we’ll make this alert statement as toast notification and instead of printing the error message on the console, we’ll display it into the server. So it is not so simple. Now let’s register this global error handler (AppErrorHandler) class into our app module.
But let’s implement a different approach, instead of registering the class as an array like this.
- providers: [
- PostService,
- AppErrorHandler
- ]
We want to tell Angular where we internally using AppErrorHandler instead of using ErrorHandler. So internally in Angular, there are multiple places where ErrorHandler class I showed you is used. So here we replace this above implementation with this new implementation.
- providers: [
- PostService,
- {
- provide: ErrorHandler,
- useClass: AppErrorHandler
- }
- ]
Provide the name of class which we want to replace and useClass is the property where we add replacement. These two properties are essential here. With the help of this object, we’re telling Angular that where we’re using ErrorHandler, we’ll use this new class AppErrorHandler.
Now let’s go back to our Posts.component and cleanup all the repetitive code. So first in ngOnInit(), we’ll completely remove this error handling function.
- ngOnInit() {
- this.service.getPosts()
- .subscribe(
- response => {
- this.posts = response.json();
- },
- error => {
- alert('An Unexpected Error Occured.');
- console.log(error);
- });
- }
So instead of handling the error here, I want the error to propogate in our application and then eventually it will hit the global error handler. So,
- ngOnInit() {
- this.service.getPosts()
- .subscribe(
- response => {
- this.posts = response.json();
- });
- }
Now in the createPost(),
- this.service.createPost(post)
- .subscribe(
- response => {
- post['id'] = response.json().id;
- this.posts.splice(0, 0, post);
- console.log(response.json());
- },
- (error: AppError) => {
- if(error instanceof BadRequest) {
- // this.form.setErrors(error.originalError);
- }
- else {
- alert('An Unexpected Error Occured.');
- console.log(error);
- }
- });
- }

BrucePosted Oct 21, 2019, 2:43 AM
One can steal the creation of a person but not his creativity. Please give credit to the originator at least.
Amit Kumar SinghPosted Oct 8, 2018, 1:11 AM
Nice One.. Thanks for Sharing !!!