Blog>
Snippets

Proper Error Handling in Angular HTTP Requests

Provide an example of how to handle errors in Angular HTTP requests using HttpErrorResponse.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get('/api/data')
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`
      );
    }
    // Return an observable with a user-facing error message.
    return throwError(
      'Something bad happened; please try again later.'
    );
  }
}
This example demonstrates how to handle errors in Angular HTTP requests. It imports the necessary modules from Angular's HttpClient library and uses RxJS operators. A service named 'DataService' is created with a method 'getData()' to perform a GET request. If an error occurs, the catchError operator calls the 'handleError()' method. This method checks if the error is client-side or a server-side error and logs details appropriately. Then it returns an observable with a generic error message, using throwError, to be handled by the component invoking the request.