Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
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

  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme