Angular error interceptor, Angular has a global error handling class called errorHandler that is used for http error handling that arise while making an HTTP request. It basically intercepts all the errors that happen in the application. The error may come in either the server-side or it may be an error from the client-side when the request fails due to any reason.
Table of Contents
- 1 Error handling in Angular with HttpClient Interceptor
- 2 Angular HttpClient error handling
- 3 Angular HTTP Error Handling in component
- 4 Catching Errors in HTTP Request using the HttpClient service in Angular?
- 5 How to use Angular interceptors to manage HTTP requests and error handling? or Angular HTTP error handling
- 6 Related Post
- 7 Source code available for download
Error handling in Angular with HttpClient Interceptor
Error handling in Angular, The HTTP request errors fall into two categories. The server-side and client-side code. The server-side might reject the request for various reasons. Whenever it does it will return the error response with the HTTP Status Codes. here are a few examples of error handling in angular those errors that are common to every HTTP request.
1. Unauthorized to access the API Service.
2. Authorized, but forbidden to access a particular resource.
3. The API End Point is invalid or does not exist.
4. Server down or some network error.
Angular HttpClient error handling
Angular httpclient error handling is the most powerful features is the ability to intercept HTTP request and handle HTTP errors. We will also look at some of the built-in error handling features of Angular .
The client-side code can also generate the error. The error may be due to a network error or an error while executing the HTTP request. we can catch the angular httpclient error at three different places.
1. Component
2. Service
3. Globally
For example, We will have a component that makes use of a service method to make an HTTP call. Eventually, the HTTP request will fail due to an incorrect endpoint and we will capture the errors.
Angular HTTP Error Handling in component
Let’s create a button which we will use to make the API call.
File Name: app.component.html
<h2>Users</h2>
<button name="users" (click) = "onUsersClick()">Get Users</button>
The following is the getUsers () method from the service. We have intentionally changed the URL so that it will result in an error.
Just a method called getUsers() which when invoked from the component will make an API call to some wrong endpoint.
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<any> {
const url = 'Some wrong url for test purpose';
return this.http.get(url);
}
}
We subscribe to the httpClient.getUser method in the component class.
import { Component, VERSION } from "@angular/core";
import { UserService } from "./service/user-service";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
users:Array<any>;
errorMessage:string;
constructor(private userService: UserService) {}
onUsersClick() {
this.userService.getUsers().subscribe(
(response) => { //Next callback
console.log('response received')
this.users = response;
},
(error) => { //Error callback
console.error('error caught in component')
this.errorMessage = error;
//throw error; //You can also throw the error to a global error handler
}
)
}
}
Catching Errors in HTTP Request using the HttpClient service in Angular?
We can also catch an error in the service, which makes the HTTP Request using the catcherror Operator as shown below. Once you handle the error, you can re-throw it back to the component for further handling.
import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable, throwError } from "rxjs";
import { catchError } from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<any> {
const url = 'Some wrong url for test purpose';
return this.http.get(url).pipe(
catchError(err=>{
console.error('error cought in service', err)
return throwError(err);
})
);
}
}
How to use Angular interceptors to manage HTTP requests and error handling? or Angular HTTP error handling
We create the Angular HTTP error handling Interceptor by creating a Global Service class, which implements the HttpInterceptor Interface. Then we will override the intercept method in that service.
Let’s have the following content in the httpInterceptor-service.ts file.
import { Injectable } from "@angular/core";
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
} from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import { Router } from "@angular/router";
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor(public router: Router) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError(error => {
console.error("error is intercept", error);
return throwError(error.message);
})
);
}
}
We will register error handling Interceptor the above file with app module. Here we simply import the HttpInterceptorService class from the service file and register it in the providers array.
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { HelloComponent } from "./hello.component";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { HttpInterceptorService } from "./Interceptor/httpInterceptor-service";
@NgModule({
imports: [BrowserModule, HttpClientModule, FormsModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true
}
],
})
export class AppModule {}
Related Post
Source code available for download
The source code is available on Stackblitz of the Error handling in Angular 11 – HttpClient and Interceptor
Demo Application URL : URL or https://errors-handling-with-angular-httpclient-and-interceptor.stackblitz.io