Published: November 08 2022

Angular - HTTP Request Error Handling with the HttpClient

This is a quick tutorial on how to handle errors when sending HTTP requests from Angular to an API using the HTTP client service (HttpClient).


How to handle HTTP request errors in Angular

The below examples show two different ways of catching and handling errors from HTTP requests sent with the Angular HttpClient. They both send an HTTP POST request to an invalid url on the Reqres API which is a fake online REST API used for testing, then assign the error to the errorMessage component property for display and log it to the console. The first example handles errors in the subscribe error callback, and the second uses the catchError operator.


Using the error callback to the RxJS subscribe method

The subscribe() method is passed an observer object with two callback functions, the next() function is called if the request is successful, the error() function is called if the request fails.

There is also a complete() function that we're not using here, it gets called after an Observable successfully emits its final value, i.e. after the next() function for an HTTP request. In this case it wouldn't be called because the Observable errors out.

ngOnInit() {
    this.http.post<any>('https://reqres.in/invalid-url', { title: 'Angular POST Request Example' }).subscribe({
        next: data => {
            this.postId = data.id;
        },
        error: error => {
            this.errorMessage = error.message;
            console.error('There was an error!', error);
        }
    })
}

Example Angular component at https://stackblitz.com/edit/angular-http-request-error-handling?file=src/app/components/post-request-error-callback.component.ts


Using the RxJS catchError operator

The Observable response from the POST request is piped to the catchError operator which handles the error and returns a new Observable that doesn't emit any values.

The function passed to subscribe() is called if the request is successful, it's the equivalent of passing an observer object with only a next() function. It isn't called here because no values are emitted after the error is handled, the Observable simply completes.

RxJS Operators

Operators in RxJS accept an input Observable and return an output Observable, multiple can be piped together in the Observable chain and they are executed before values are emitted to subscribers. With the catchError operator you have the added options of returning a fallback value to subscribers when there is an error, or rethrowing a custom error using the RxJS throwError() function. For more info on RxJS operators see https://rxjs.dev/guide/operators.

ngOnInit() {
    this.http.post<any>('https://reqres.in/invalid-url', { title: 'Angular POST Request Example' })
        .pipe(catchError((error: any, caught: Observable<any>): Observable<any> => {
            this.errorMessage = error.message;
            console.error('There was an error!', error);

            // after handling error, return a new observable 
            // that doesn't emit any values and completes
            return of();
        }))
        .subscribe(data => {
            this.postId = data.id;
        });
}

Example Angular component at https://stackblitz.com/edit/angular-http-request-error-handling?file=src/app/components/post-request-catch-error.component.ts

 


Need Some Angular Help?

Search fiverr for freelance Angular developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by