Introduction
In this article, we will see the various errors that occurred while requesting from the client to the server. Also, we will create a sample component and try to console the error object.
Prerequisites
The call to the server doesn't always succeed. Sometimes, it fails.
- ngOnInit() {
- this.service.getPosts()
- .subscribe(response=> {
- console.log(response.json());
- this.posts = response.json();
- });
- }
-
- private url = 'http://jsonplaceholder.typicode.com/posts';
Let’s change the URL to an invalid URL:
- private url = 'http://jsonplaceholder404.typicode.com/posts';
Now run the application. You will see that no items have posted, as you have given an unknown URL. We need to change our implementation to handle errors and give proper error messages to our user.
When we try to handle error we will encounter two types of error.
- Unexpected Error
- Expected Error
There are three types of unexpected error - Server is Offline ( The client is sending a request to the server but the server is not up and responding to the client request), Network is down (when the server is online but the client is not able to reach server ) and unhandled exceptions (server is up and responding and the network is fine, but there are some API related bugs).
There are two types of Expected errors that we need to handle: “Not Found” error 404, and “Bad request” error 400.
If we have a list of items visible on two different clients. If one client deletes an item (say id:101) then the representation view of the second client will not update. Furthermore, if the second client requests to delete the same item (say id: 101) then the server will respond with a 404 error that the item is not found. This occurs in most cases, that’s why this type of error comes under expected error.
The expected error, Bad request is generated when the server responds to the client that the request is bad. Suppose you already registered an email/phone to the server and you try to register the same. Then, the server with their proper check responds with the bad request. This also comes under expected errors.
So we have to handle the expected and unexpected errors properly while developing an application.
Let's start creating the application.
Click here to create the component in which we going to add errors in the service request.
Change the URL to as below in postService.ts to check the getPost method.
- private url = 'http://jsonplaceholder404.typicode.com/posts';
Change PostsComponent as below,
The subscribe method has an optional parameter named “error”. The type of this parameter is a function that we need to pass that takes an error object and return void. Let’s handle the expected errors.
- import { Component, OnInit } from '@angular/core';
- import { PostService } from '../services/post.service';
-
- @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) => {
- console.log('An unexpected error occured');
- console.log(error);
- }, () => {
- console.log('completed');
- });
- }
-
- 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);
- }, (error: Response) => {
- if(error.status == 400)
- console.log(error.json());
- else {
- console.log('An unexpected error occured');
- console.log(error);
- }
- });
- }
-
- updatePost(post)
- {
- this.service.updatePost(post)
- .subscribe(response=> {
- console.log(response.json);
- }, error => {
- console.log('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);
- console.log(response.json);
- }, (error: Response) => {
- if(error.status == 404)
- console.log('Already deleted')
- else {
- console.log('An unexpected error occured');
- console.log(error);
- }
-
- })
- }
- }
You can see the below error when you run the application:
Change the URL to the correct one and test all other methods.
Now call create, update, delete request by giving the invalid values and find out what error are occurred that you can handle on your own. By displaying on toast message, by notification, by error message, or by any other alert mechanism. You can create the error logs by inserting the error messages in some standalone file or in database. It is all up to you what information you want to keep or using when error occurred. In a large scale application, error handling is one of the most important mechanism that is being implemented so as to track the efficient working of the application by handling it in different ways programmatically.
- ngOnInit() {
- this.service.getPosts()
- .subscribe(response=> {
- this.posts = response.json();
- }, (error) => {
- console.log('An unexpected error occured');
- console.log(error);
- }, () => {
- console.log('completed');
- });
- }
In the above method, we have one more optional parameter that indicates complete.
If the request is successfully completed, then it will execute. If an error occurred, then the error optional method will execute. You can go through details.
Is the implementation for error handling good enough?
The above implementation is not good enough, as we have so many ugly implementations in PostComponent related to handling the error through Response and error code. This should be checked on service and the application-specific error object should be thrown from the service.
Let's start implementing:
Add three error files app-error.ts, not-found-error.ts, bad-request-error.ts,
- export class AppError {
- constructor(originalError?: any) {
- }
- }
- import { AppError } from './app-error';
- export class NotFoundError extends AppError{
-
- }
- import { AppError } from './app-error';
- export class BadRequestError implements AppError{
-
- }
Modify PostService (post.service.ts):
- import { Http } from '@angular/http';
- import { Injectable } from '@angular/core';
- import { HttpErrorResponse } from '@angular/common/http';
- import { throwError } from 'rxjs';
- import { AppError } from '../common/app-error';
- import { NotFoundError } from '../common/not-found-error';
- import { BadRequestError } from '../common/bad-request-error';
- import { catchError } from 'rxjs/operators';
-
- @Injectable({
- providedIn: 'root'
- })
- export class PostService {
- private url = 'http://jsonplaceholder.typicode.com/posts';
- constructor(private http: Http) { }
-
- getPosts(){
- return this.http.get(this.url)
- .pipe(catchError(this.handleError));
- }
- createPost(post){
- return this.http.post(this.url, JSON.stringify(post))
- .pipe(catchError(this.handleError));
- }
- updatePost(post){
- return this.http.patch(this.url + '/' + post.id, JSON.stringify({isRead: true}))
- .pipe(catchError(this.handleError));
- }
- deletePost(id){
- return this.http.delete(this.url + '/' + id)
- .pipe(catchError(this.handleError));
- }
- handleError(error: HttpErrorResponse){
- if(error.status == 400)
- return throwError(new BadRequestError());
- if(error.status == 404)
- return throwError(new NotFoundError());
- else
- return throwError(new AppError());
- }
- }
Modify PostComponent (post.component.ts):
- import { Component, OnInit } from '@angular/core';
- import { PostService } from '../services/post.service';
- import { NotFoundError } from '../common/not-found-error';
- import { AppError } from '../common/app-error';
- import { BadRequestError } from '../common/bad-request-error';
-
- @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: AppError) => {
- if(error instanceof NotFoundError)
- console.log('Not Found Error');
- else if(error instanceof BadRequestError)
- console.log('Bad Request Error');
- else
- console.log('App Error');
- }, () => {
- console.log('completed');
- });
- }
-
- 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);
- }, (error: AppError) => {
- if(error instanceof NotFoundError)
- console.log('Not Found Error');
- else if(error instanceof BadRequestError)
- console.log('Bad Request Error');
- else
- console.log('App Error');
- });
- }
-
- updatePost(post)
- {
- this.service.updatePost(post)
- .subscribe(response=> {
- console.log(response.json);
- }, (error: AppError) => {
- if(error instanceof NotFoundError)
- console.log('Not Found Error');
- else if(error instanceof BadRequestError)
- console.log('Bad Request Error');
- else
- console.log('App Error');
- })
- }
-
- deletePost(post)
- {
- this.service.deletePost(post.id)
- .subscribe(response=> {
- let index = this.posts.indexOf(post);
- this.posts.splice(index, 1);
- console.log(response.json);
- }, (error: AppError) => {
- if(error instanceof NotFoundError)
- console.log('Not Found Error');
- else if(error instanceof BadRequestError)
- console.log('Bad Request Error');
- else
- console.log('App Error');
- })
- }
- }
Now you will get the application specific error. You can define the error message and status code and use that application specific error object to use further in our component. Instead of checking for Response error and check for error status and then defining the error usage, we should add an application-specific error handling mechanism and use them in our application.
Thank you!