How to handle exceptions in Angular service

A service in angular has special duties such as fetching and pushing data from the server and to the server. The service can be used by any components.

Handle exception

To hand service exceptions we need the following two libraraies

import {catchError} from 'rxjs/operators';
import { throwError } from 'rxjs';

In the service.ts file we need to handle the error using pipe function as follows

   Post(model : Model){
   return   ('http:\apiurl',model).pipe(catchError(this.ErrorHandler));
  ErrorHandler(error: HttpErrorResponse): any {
    return throwError(error);

Catching the error in component

For the receiving the error in a component , we need to create property then assign the error object to the property. So that we can bind it to the template.

    this._service.Post( any) => console.log('Success', data), (error: any) => this.errorMsg = error.statusText);

Don’t forget to visit the source code page

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.