Skip to main content

Error Handling

Error handling is a crucial part of any application's development process. In Angular, the HTTP Client is used to handle HTTP requests and responses. However, it's not always a smooth sailing process, and we may encounter errors during this communication. This tutorial will guide you through the process of handling these errors effectively.

As a prerequisite, you should have a basic understanding of Angular and the HTTP Client.

HTTP Error Response

The HTTP protocol returns a status code for every request. A status code in the range of 200-299 indicates success, while codes in the 400-599 range indicate an error. The HTTP Client in Angular captures these errors and treats them as Observable errors.

Catch and Handle Errors

The HTTP Client method in Angular uses RxJS observables. To handle these errors, you can use the catchError operator from RxJS.

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

this.http.get('api/url').pipe(
catchError(error => {
// handle your error here
console.error(error);
return throwError('Something bad happened; please try again later.');
})
);

In the above code snippet, we are subscribing to an HTTP GET request. If an error occurs, the catchError operator will catch it and pass it to the error handling function. This function can then process the error and return an observable error using the throwError function.

HTTP Error Object

The error object returned by the HTTP Client in Angular has the following properties:

  • error: Contains the error returned by the server. It could be a string or an object.
  • headers: The headers that were associated with the request.
  • message: A user-readable error message.
  • name: The name of the error, usually 'HttpErrorResponse'.
  • ok: Will be 'false'.
  • status: The HTTP status code.
  • statusText: The HTTP status text.
  • url: The URL of the request.

You can use these properties to customize your error handling function.

catchError(error => {
let errorMsg: string;
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
errorMsg = `An error occurred: ${error.error.message}`;
} else {
// The backend returned an unsuccessful response code.
errorMsg = `Server returned code: ${error.status}, error message is: ${error.message}`;
}
console.error(errorMsg);
return throwError('Something bad happened; please try again later.');
})

Retry Failed HTTP Requests

Sometimes, the error might be temporary, and simply retrying the HTTP request might solve the issue. You can use the retry operator from RxJS for this.

import { retry, catchError } from 'rxjs/operators';

this.http.get('api/url').pipe(
retry(3), // retry a failed request up to 3 times
catchError(error => {
// handle your error here
console.error(error);
return throwError('Something bad happened; please try again later.');
})
);

In this example, if the HTTP request fails, it will be retried up to 3 times before the error is passed to the catch block.

Error Handling Service

For better code structure and reusability, you can create a service to handle your HTTP errors.

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

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

handleError(error: HttpErrorResponse) {
let errorMsg: string;
if (error.error instanceof ErrorEvent) {
errorMsg = `An error occurred: ${error.error.message}`;
} else {
errorMsg = `Server returned code: ${error.status}, error message is: ${error.message}`;
}
console.error(errorMsg);
return throwError('Something bad happened; please try again later.');
}
}

Then, use this service in your HTTP request.

import { retry, catchError } from 'rxjs/operators';
import { ErrorHandlerService } from './error-handler.service';

constructor(private errorHandlerService: ErrorHandlerService) {}

this.http.get('api/url').pipe(
retry(3),
catchError(this.errorHandlerService.handleError)
);

That's it! You've learned how to handle errors in Angular's HTTP Client effectively. Remember that good error handling can greatly improve your application's robustness and user experience. Happy coding!