Error handling in Angular involves capturing and managing errors to ensure a smooth user experience and easier debugging. Angular provides several built-in tools and techniques for handling errors systematically.

1. Handling HTTP Errors

When making HTTP requests, you can handle errors using the HttpClient and the catchError operator from RxJS.

Example

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

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private apiUrl = 'https://api.example.com/data';

  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get(this.apiUrl).pipe(
      catchError(this.handleError)
    );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // Client-side error
      console.error('Client-side error:', error.error.message);
    } else {
      // Server-side error
      console.error(`Server-side error: ${error.status} - ${error.message}`);
    }
    return throwError(() => new Error('Something went wrong; please try again later.'));
  }
}

2. Global Error Handling

Angular provides a way to handle application-wide errors using the ErrorHandler service.

3. Error Interceptors

Use an HTTP interceptor to handle errors globally for all HTTP requests.

Example

4. Using Angular Guards for Route Error Handling

Angular guards can protect routes and handle access-related errors.

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean {
    const isAuthenticated = false; // Replace with actual authentication logic
    if (!isAuthenticated) {
      alert('You are not authorized to access this page.');
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

5. Error Display in the UI

Display user-friendly error messages in the UI using Angular components.

Example

6. RxJS Error Handling Strategies

7. Logging Errors

Use external services like Sentry, LogRocket, or custom logging services to log errors.

Example

@Injectable({
  providedIn: 'root'
})
export class LoggingService {
  logError(message: string, stack: string) {
    // Send error logs to an external server
    console.log('Logging error:', message);
  }
}

Summary

This article will help to understand error handling in different ways and hope it will help in your application.