0
0
Angularframework~5 mins

catchError for error handling in Angular

Choose your learning style9 modes available
Introduction

catchError helps you handle errors in Angular when working with streams. It stops the error from breaking your app and lets you respond nicely.

When calling a web service and you want to handle failures gracefully.
When you want to show a friendly message if data loading fails.
When you want to log errors without stopping the app.
When you want to provide a default value if something goes wrong.
Syntax
Angular
import { catchError } from 'rxjs/operators';

observable$.pipe(
  catchError(error => {
    // handle error here
    return fallbackObservable;
  })
);

Use catchError inside the pipe() method of an Observable.

It takes a function that receives the error and returns a new Observable.

Examples
Returns a simple fallback string wrapped in an Observable when an error occurs.
Angular
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';

observable$.pipe(
  catchError(error => of('Error happened'))
);
Logs the error and returns an empty array as fallback data.
Angular
observable$.pipe(
  catchError(error => {
    console.error('Error:', error);
    return of([]);
  })
);
Sample Program

This Angular component tries to load data but simulates an error. catchError catches the error, sets an error message, and returns default data instead. The template shows the data or error message.

Angular
import { Component } from '@angular/core';
import { of, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-error-demo',
  template: `
    <div *ngIf="data; else errorTpl">Data: {{ data }}</div>
    <ng-template #errorTpl><div>Error: {{ errorMessage }}</div></ng-template>
  `
})
export class ErrorDemoComponent {
  data: string | null = null;
  errorMessage: string | null = null;

  constructor() {
    this.loadData().subscribe({
      next: value => this.data = value,
      error: err => this.errorMessage = err.message
    });
  }

  loadData() {
    // Simulate an error Observable
    return throwError(() => new Error('Failed to load')).pipe(
      catchError(err => {
        this.errorMessage = err.message;
        return of('Default data');
      })
    );
  }
}
OutputSuccess
Important Notes

catchError must return an Observable to keep the stream alive.

If you don't handle errors, your Observable will stop and may break your app.

Summary

catchError helps handle errors in Observable streams.

Use it inside pipe() to catch and respond to errors.

Always return a new Observable inside catchError to continue the stream.