How to handle HTTP errors in Angular

Handling HTTP errors gracefully is crucial for robust Angular applications, providing users with meaningful feedback when network requests fail. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented error handling in countless Angular enterprise applications and admin dashboards. From my 25 years of experience in web development and 11 years with Angular, the most effective approach is to use the catchError operator with RxJS to intercept and handle HTTP errors consistently. This pattern provides centralized error management and improved user experience.

Use the catchError operator from RxJS to intercept and handle HTTP errors in your service methods.

import { Injectable } from '@angular/core'
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {}

  getUsers(): Observable<any> {
    return this.http.get('/api/users').pipe(
      catchError(this.handleError)
    )
  }

  private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      console.error('Network error:', error.error)
    } else {
      console.error(`Backend returned code ${error.status}, body:`, error.error)
    }
    return throwError(() => new Error('Something went wrong; please try again later.'))
  }
}

The catchError operator intercepts any HTTP errors from the request stream. The handleError method receives an HttpErrorResponse object containing error details like status code and error message. You can check error.status to handle different types of errors - network errors return status 0, while server errors return HTTP status codes like 404 or 500. After logging or processing the error, return throwError() to propagate a user-friendly error message to components.

This is the same robust error handling pattern we use in CoreUI Angular admin templates to ensure reliable API communication. For global error handling, implement an HTTP interceptor that catches errors across all requests automatically.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team