0
0
AngularDebug / FixBeginner · 4 min read

How to Handle HTTP Error in Angular: Simple Guide

In Angular, handle HTTP errors by using the 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:

typescript
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');
  }
}
Output
If the HTTP request fails, the error will not be caught and may cause unhandled exceptions or silent failures.
🔧

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.

typescript
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.'));
      })
    );
  }
}
Output
When an HTTP error happens, the error is caught, logged, and a user-friendly error is thrown for the component to handle.
🛡️

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.

Key Takeaways

Use RxJS catchError to handle HTTP errors in Angular services.
Log errors and provide user-friendly messages or fallback data.
Consider using HttpInterceptor for centralized error handling.
Check error status codes to handle different error types specifically.
Enable strict linting to catch missing error handling early.