Back to course

Error Handling in HTTP Calls

The Complete Angular Developer: From Zero to Hero

29. Error Handling in HTTP Calls

APIs inevitably return errors (e.g., 404 Not Found, 500 Server Error, 401 Unauthorized). Robust applications must handle these failures gracefully. Since HttpClient returns Observables, we use RxJS operators, specifically catchError and the error callback in the subscription.

1. Handling Errors in the Subscription

The most basic approach is using the error callback defined in the subscribe object (as shown previously).

typescript this.dataService.getUsers().subscribe({ next: (data) => { /* success */ }, error: (httpError) => { // This handles errors triggered by the request (4xx or 5xx) console.error('HTTP Error:', httpError); this.errorMessage = httpError.message; } });

2. Using the catchError RxJS Operator (In the Service)

If you want to handle the error or transform it before the component subscribes, use the catchError operator, which must be imported from rxjs/operators.

typescript // data.service.ts import { catchError } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; import { HttpErrorResponse } from '@angular/common/http';

private handleError(error: HttpErrorResponse) { let errorMessage = 'An unknown error occurred!'; if (error.error instanceof ErrorEvent) { // Client-side error or network error errorMessage = Client Error: ${error.error.message}; } else { // Backend returned an unsuccessful response code. errorMessage = Server Error: ${error.status} - ${error.message}; } console.error(errorMessage); // Return an observable with a user-facing error message return throwError(() => new Error(errorMessage)); }

getUsersWithCatch(): Observable<User[]> { return this.http.get<User[]>(${this.baseUrl}/users-error-url).pipe( // Add the catchError operator to the observable chain catchError(this.handleError) ); }

By handling the error in the service, the component only sees a single stream (either successful data or the customized error Observable), which simplifies component logic.