In this article we are going to discuss about Global Error Handling in Angular. We also learn how to use Angular to build a Global Error Handler or a custom error handler. We discover why we must manage errors and some of the best practices. Finally, we will learn how to inject services into the general error handler, as well as how to display a user notification page. Please read my previous article Understanding of HttpClient in Angular.
Why it need to Handle Errors?
Handling errors is the most important part of application development. These errors hinder our work, the application can throw an error when something goes wrong. Angular handles the errors, but it does nothing except writing it in the console. Well, that is not useful either to the user or to the developer. Unexpected errors can happen any time, like a connection break, a null exception, no internet access, an unauthorized user, or a session expired.
There are two types of error handling mechanism in Angular.
- Client-side Errors
- HTTP Errors.
HTTP Errors
The HTTP Errors are thrown when you send an HTTP Request using the HTTPClient
Module. These errors again fall into two categories. One is generated by the server like an unauthorized user, session expired, Server down, etc. The other one is generated at the client-side while trying to generate the HTTP Request. These errors could be network error, error while generating the request, etc.
Client-side HTTP errors
All errors that occur by a code are called client-side HTTP errors. It shows there is something wrong in the code.
To handle such type of issues, there are two ways to handle these errors in Angular.
- Default Error Handling
- Global Error Handling
Default Error Handling
In this approach, we can simply use the try-catch method for handling the error. It is a traditional way to handle these errors.
handleerror()
{
try
{
// Your code here
}
catch(error)
{
// handle error here
}
}
Global Error Handling
The built-in ErrorHandler is a basic solution that can be used while developing the app. However, it is ineffective in determining the error that occurred in the production environment. The errors that occur on the end of the customer are unknown to us.
Why it advisable to create our own global error handler class.
- We can show a simple error page to the user, with a option to retry the operation.
- We can log the errors back to the back end server, where we can read all the errors. Then we can make necessary changes to the app to remove the error
Creating Global Error Handler
Here we created the GlobalErrorHandlerService
which implements the ErrorHandler
Then, override the handleError(error)
method and handle the error.
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandlerService implements ErrorHandler {
constructor() {
}
handleError(error: any) {
console.error('This is custom error log :', error.message);
console.log(error.message)
}
}
Next, register the GlobalErrorHandlerService
in the Application root module(app.module.ts
) using the token ErrorHandler
like below highlighted.
@NgModule({
declarations: [
AppComponent,
ProductAComponent,
ProductBComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandlerService },
],
bootstrap: [AppComponent]
})
In the example below, I’ve made two components, and you can see when the error throws it automatically and it’s captured under Global Error Handler.
Here we have created the component that manually throws error like below.
throwError1() {
throw Error('The product component-A has thrown an error!');
}
import { Component } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-product-b',
templateUrl: './product-b.component.html',
styleUrls: ['./product-b.component.css']
})
export class ProductBComponent {
users = new Array<any>();
constructor(public userService: UserService) { }
ngOnInit(): void { }
throwError1() {
throw Error('The product component- B has thrown an error!');
}
getUsers() {
this.userService.getUsers1().subscribe(
result => {
// Handle result
this.users = result.data;
console.log(result)
},
error => {
throw Error("There is some issues to communicate to API");
});
}
}
Best Practices in Handling Errors
Now that we’ve learned how to handle errors, here are a few things to consider when creating an Error Handler service.
- Use a try.. catch block to handle the known errors. Handle it accordingly. If you are not able to handle it, then re-throw it.
- Use a global error handler to trap all unhandled errors and show a notification to the user.
- The ErrorHandler does not trap HTTP Errors, You need to Use HTTP Interceptors to handle HTTP Errors.
- Check for type of error in the error handler and act accordingly. For Example, if is an error from the back end (HTTP Error) you can use the HTTP Status Code to take necessary action.
- 401 Unauthorized error you can redirect the user to the login page.
- 500 Internal Server Error you can ask the user to retry after some time while sending a notification to the server administrator.
Conclusion
We discussed here about Global Error Handling in Angular. Here gone through how and why we use Error handling in Angular.
Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding 🙂
Related Articles
- Create a responsive sidebar with Angular Material- Angular 18 Example Series
- How to Deploy Angular 17/18 App in GitHub Pages
- How to convert Text To Speech With Azure Cognitive Services using Angular and .Net Core
- Angular Interceptors- The Complete Guide
- Upload Download and Delete files in Azure Blob Storage using ASP.NET Core and Angular
- How to use Policy-based Authorization using JWT in .Net Core 7 and Angular
- How to deploy Angular App in Azure Static Web App
- Global Error Handling in Angular
- How to host Angular app on AWS S3 bucket using CloudFront
- How to Deploy Angular App in GitHub Pages
SUPPORT ME