Why 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.
How to handle such type of errors?
There are two ways to handle these errors in Angular.
- Default Error Handling
- Global Error Handling
Default Error Handling
In this approch, we can simply use the try-catch method for handling the error. It is a traditional way to handle these errors.
Syntax
- handelerror()
- {
- try
- {
-
- }
- catch(error)
- {
-
- }
- }
Global Error Handling
Global Error Handling in Angular is handled by the Errorhandler class which is part of the @angular/core module. This is a global error handler class which catches all exceptions thrown by the application. In this approach, we create a class that will be implemented by the ErrorHandler class.
Syntax
- import { ErrorHandler, Injectable } from '@angular/core';
-
- @Injectable()
- export class Myerrorhandelor implements ErrorHandler {
- constructor() {
- }
- handleError(error) {
- console.error('An error occurred:', error.message);
- console.error(error);
- alert(error);
- }
- }
App.Module.ts
- import { BrowserModule } from '@angular/platform-browser';
- import { NgModule, ErrorHandler } from '@angular/core';
-
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
- import { Myerrorhandelor } from "./myerrorhandelor";
- @NgModule({
- declarations: [
- AppComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule
- ],
- providers: [{provide: ErrorHandler, useClass: Myerrorhandelor}],
- bootstrap: [AppComponent]
- })
- export class AppModule { }
Summary
I hope you have learned from this article. It is a very useful functionality and it will help you.