0
0
Angularframework~5 mins

Handling HTTP errors in Angular

Choose your learning style9 modes available
Introduction

Handling HTTP errors helps your app respond nicely when something goes wrong with data requests. It keeps users informed and prevents crashes.

When fetching data from a server and the server is down or unreachable.
When a user submits a form and the server returns an error response.
When loading images or files from an external source that might fail.
When your app depends on APIs that might return errors or invalid data.
Syntax
Angular
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

this.http.get('url').pipe(
  catchError(error => {
    // handle error here
    return throwError(() => new Error(error.message));
  })
).subscribe(
  data => { /* use data */ },
  error => { /* handle error in subscription */ }
);

Use catchError inside pipe() to catch errors from HTTP calls.

Return throwError to pass the error to the subscriber.

Examples
Logs error to console and shows alert with a friendly message.
Angular
this.http.get('api/data').pipe(
  catchError(err => {
    console.error('Error occurred:', err.message);
    return throwError(() => new Error('Failed to load data'));
  })
).subscribe(
  data => console.log(data),
  error => alert(error.message)
);
Handles specific HTTP status codes differently.
Angular
this.http.post('api/save', payload).pipe(
  catchError(err => {
    if (err.status === 404) {
      return throwError(() => new Error('Resource not found'));
    }
    return throwError(() => new Error('Unknown error'));
  })
).subscribe(
  response => console.log('Saved'),
  error => console.log(error.message)
);
Sample Program

This Angular component tries to load data from a wrong URL to simulate an error. It shows a red error message when the HTTP call fails.

Angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Component({
  selector: 'app-error-demo',
  template: `
    <button (click)="loadData()">Load Data</button>
    <p *ngIf="errorMessage" style="color: red;">{{ errorMessage }}</p>
    <pre *ngIf="data">{{ data | json }}</pre>
  `
})
export class ErrorDemoComponent {
  data: any = null;
  errorMessage = '';

  constructor(private http: HttpClient) {}

  loadData() {
    this.errorMessage = '';
    this.data = null;
    this.http.get('https://jsonplaceholder.typicode.com/invalid-url')
      .pipe(
        catchError(err => {
          this.errorMessage = 'Failed to load data: ' + err.message;
          return throwError(() => new Error(err.message));
        })
      )
      .subscribe({
        next: res => this.data = res,
        error: () => {}
      });
  }
}
OutputSuccess
Important Notes

Always handle errors to avoid app crashes and improve user experience.

You can customize error messages based on error status or content.

Use Angular's HttpClient and RxJS operators for clean error handling.

Summary

Use catchError inside pipe() to catch HTTP errors.

Return throwError to pass errors to subscribers.

Show friendly messages to users when errors happen.