Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • PDF Invoice Generator
Menu

Angular 14 HTTP Error Handling Using Pipe,CatchError and ThrowError Full Example

Posted on January 14, 2023

 

 

Here is an example of how to handle HTTP error in Angular using the Pipe, CatchError, and ThrowError operators:

 

  1. Import the necessary modules:

 

TypeScript
1
2
3
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap } from 'rxjs/operators';
import { throwError } from 'rxjs';

 

 

In your component, inject the HttpClient:

 

 

1
constructor(private http: HttpClient) { }

 

 

  1. In your component, create a method to make the API call and handle errors:

 

 

TypeScript
1
2
3
4
5
6
7
8
getData() {
    this.http.get('https://jsonplaceholder.typicode.com/todos/1')
    .pipe(
        tap(data => console.log(data)),
        catchError(this.handleError)
    )
    .subscribe();
}

 

 

  1. Create a separate method to handle errors:
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
        // A client-side or network error occurred. Handle it accordingly.
        console.error('An error occurred:', error.error.message);
    } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong.
        console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
        'Something bad happened; please try again later.');
};

Recent Posts

  • Build a Fixed Deposit Interest Calculator Using Amount and Time in Browser Using HTML5 & Javascript
  • How to Download Files From URL in Node.js Using Node-Downloader-Helper Library
  • Angular 10 Image Carousel and Video Gallery Lightbox Modal Slider Using ng-image-slider Library
  • React Unsplash Api Photo Search App
  • React Form Validation Using Formik and Yup
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • javascript
  • Koajs
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme