How to Handle HTTP Error in Angular: Simple Guide
catchError operator from RxJS inside your service's HTTP call. This lets you catch errors and respond gracefully, such as showing a message or retrying the request.Why This Happens
HTTP errors occur when a request to a server fails due to network issues, server problems, or invalid responses. Without error handling, your Angular app may crash or behave unexpectedly.
Here is an example of broken code that does not handle HTTP errors:
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) {} getData() { return this.http.get('https://api.example.com/data'); } }
The Fix
Use the catchError operator from RxJS to catch HTTP errors and handle them properly. You can return a fallback value or throw a user-friendly error.
This prevents your app from crashing and allows you to show error messages or retry logic.
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) {} getData() { return this.http.get('https://api.example.com/data').pipe( catchError(error => { console.error('HTTP error occurred:', error); // Return fallback data or rethrow error return throwError(() => new Error('Failed to load data, please try again later.')); }) ); } }
Prevention
Always use catchError in your HTTP calls to handle errors gracefully. Combine it with user notifications or retry strategies for better user experience.
Use Angular's HttpInterceptor to centralize error handling for all HTTP requests.
Enable strict TypeScript settings and linting rules to catch missing error handling during development.
Related Errors
Common related errors include:
- Network errors: No internet connection causes HTTP requests to fail.
- Timeout errors: Server takes too long to respond.
- Unauthorized errors (401): User is not authenticated.
Each can be handled specifically in catchError by checking error.status.