Catch Global HTTP Errors in Angular with Interceptors
Written on
Introduction to Global Error Handling
For developers working with Angular and Web APIs, dealing with HTTP errors is a routine challenge. If you’re looking for a reliable method to consistently capture and display these errors, you're in the right place. This guide will walk you through the implementation process using Angular 14 and Bootstrap 5.
In Figure 1, you can see an example of how errors are displayed in a modal dialog, complete with HTTP status codes, descriptions, and detailed messages.
Technical Overview
To effectively manage global errors in Angular, you’ll need to create an HTTP interceptor. This involves creating a new class that adheres to the HttpInterceptor interface from the @angular/common package. This interface mandates the implementation of a method named intercept, which accepts two parameters: an incoming HttpRequest object and a HttpHandler.
Figure 2 demonstrates the relationship between the Angular client and the Web API server. HTTP interceptors serve as intermediaries, capturing and processing HTTP requests and responses exchanged between the client and the backend server. By registering these interceptors within the root module of your Angular application, you can seamlessly catch both 4xx client errors and 5xx server errors. If you have experience with the .NET stack, you can think of interceptors as analogous to the .NET Middleware pipeline. For additional insights into HTTP interceptors, refer to the section on Angular HTTP interceptors.
Tutorial Overview
This tutorial is divided into two main parts:
- Implementing code to handle global errors in Angular via an HTTP interceptor.
- Testing the interceptor by making HTTP requests and verifying proper error handling.
Part 1: Implementing Global Error Handling
To set up global error handling in Angular using an HTTP interceptor, follow these steps:
- Create the Interceptor Class: Develop a class named ErrorHandlerInterceptor that implements the HttpInterceptor interface. This class will house the logic for error management. Refer to Figure 3 for the source code of error-handler.interceptor.ts.
- Use the catchError() Operator: Inside the ErrorHandlerInterceptor, leverage the catchError() operator to capture errors occurring during HTTP requests. This operator allows you to manage errors effectively, such as logging them or showing an error message to users. See Figure 3, line 24 for details.
- Implement Error Handling Logic: In the ErrorHandlerInterceptor, create a function called errorHandler (see Figure 3, line 28) that logs errors or displays messages. This function should be invoked whenever an error is caught using the catchError() operator. For demonstration purposes, this function calls another function, openDialog (see Figure 3, line 32), to show the error details.
- Register the Interceptor: In your Angular app module, import the ErrorHandlerInterceptor class (refer to Figure 4, line 11) and add it to the providers array (Figure 4, lines 38–42). This ensures the interceptor processes all HTTP requests in your application.
- Create a Modal Dialog Service: Build a Bootstrap modal display service called ErrorDialogService using the NgbModal service from the @ng-bootstrap/ng-bootstrap package. The open() method on line 13 opens a modal featuring the ErrorDialogComponent. Lines 14–17 pass the error status, status text, URL, and message for display.
- Develop the Error Dialog Component: Create the ErrorDialogComponent to show error details. Refer to Figure 5 and Figure 6 for the source code of error-dialog.component.html and error-dialog.component.ts, respectively. Figure 5 contains the HTML/Bootstrap modal code, while Figure 6, lines 12–16, includes the Angular TypeScript code that accepts five input parameters.
Part 2: Testing the Interceptor
Now it's time to test your implementation! You can download the complete project from GitHub. After downloading and opening the code in your preferred IDE (I recommend Visual Studio Code), run the following commands to install third-party modules and launch the Angular app locally:
npm install
npm start
To monitor the network activity, open the browser's developer console by pressing F12, navigate to the Network tab, and look for the API call to "random." See Figure 9 for a visual reference.
To validate the global error handling, open quote.service.ts located in src/app/home and modify the REST API call to introduce an error. For instance, change the REST API resource from jokes to jokes2 at line 8. See Figure 10 for guidance.
After making this change, you should see the Bootstrap modal dialog displaying detailed error information, as shown in Figure 11. If your developer console is open, you can examine the error details in the Network tab.
Congratulations! You have successfully implemented global HTTP error handling in Angular.
Source Code Repository
Feel free to download and experiment with the source code from the following link:
Summary of the Tutorial
HTTP interceptors offer a robust method for managing HTTP requests and responses on a global scale, eliminating the need for repetitive code in individual components or services. Their versatility allows for a variety of applications, such as adding default headers to all outgoing requests, logging HTTP traffic, or centrally managing HTTP errors.
By adopting this approach, you can guarantee that any issues arising from REST API calls in Angular are logged efficiently, aiding developers in identifying and resolving problems, thereby enhancing the overall user experience.
In this video titled "Global error handling in angular using interceptor," you'll find practical insights into managing errors effectively in Angular applications.
The second video, "Http Error handling in angular 13 | Exception handling globally using interceptor," offers a detailed overview of error handling mechanisms in Angular 13.