Handle Http errors with RxJS catchError
Step 9 — Adding HTTP Error Handling with RxJS catchError()
& HttpClient
In this step, we'll proceed to add error handling in our example application.
The Angular's HttpClient methods can be easily used with the catchError()
operator from RxJS, since they return Observables, via the pipe()
method for catching and handling errors. We simply need to define a method to handle errors within your service.
There are two types of errors in front-end applications:
- Client-side errors such as network issues and JavaScript syntax and type errors. These errors return
ErrorEvent
objects. - Server-side errors such as code errors in the server and database access errors. These errors return HTTP Error Responses.
As such, we simply need to check if an error is an instance of ErrorEvent
to get the type of the error so we can handle it appropriately.
Now, let's see this by example. Open the src/app/data.service.ts
file and update it accordingly:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from "@angular/common/http";
import { throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
private REST_API_SERVER = "<http://localhost:3000/products>";
constructor(private httpClient: HttpClient) { }
handleError(error: HttpErrorResponse) {
let errorMessage = 'Unknown error!';
if (error.error instanceof ErrorEvent) {
// Client-side errors
errorMessage = `Error: ${error.error.message}`;
} else {
// Server-side errors
errorMessage = `Error Code: ${error.status}\\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}
public sendGetRequest(){
return this.httpClient.get(this.REST_API_SERVER).pipe(catchError(this.handleError));
}
}
As you can see, this needs to be done for each service in your application which is fine for our example since it only contains one service but once your application starts growing with many services which may all throw errors you need to use better solutions instead of using the handleError
method per each service which is error-prone. One solution is to handle errors globally in your Angular application using HttpClient interceptors.
This is a screenshot of an error on the console if the server is unreachable:
In the next step, we'll see how to improve our data service by automatically retry sending the failed HTTP requests.