Here is an example of how to handle HTTP error in Angular using the Pipe, CatchError, and ThrowError operators:
- Import the necessary modules:
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) { } |
- In your component, create a method to make the API call and handle errors:
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(); } |
- Create a separate method to handle errors:
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.'); }; |