Errors are the unexpected issue or problem that occurs during the execution of a program. Incorrect syntax, invalid input, system failures or bug in API logic could be the possible reasons for these errors. These errors may affect the user experience in negative way, hence, it is necessary to handle them at compile time.
Error handling is the process of detecting and resolving these errors or exceptions before execution. Angular provides a number of ways to handle the errors that we are going to learn in this tutorial.
Handling Errors in Angular
There are multiple ways to handle errors in Angular, which are given below −
Using ErrorHandler Class
The ErrorHandler is a built-in class of the Angular @angular/core package. It provides a hook to catch errors globally. When something goes wrong, like any unhandled exception occurs anywhere in the application, this class catches that exception and prints the error messages on console.
Remember! the ErrorHandler class simply prints the error message so that developers can see what went wrong and fix it. However, you can replace this default behavior by creating a custom ErrorHandler.
Extend the ErrorHandler class and override its handleError() method as shown below to create a custom behavior of this class −
import{ Injectable, ErrorHandler }from'@angular/core'; @Injectable({ providedIn:'root'})exportclassGlobalErrorHandlerimplementsErrorHandler{handleError(error: any):void{// Log the error to an external service or display a messageconsole.error("An error occurred:", error);// Create any custom behavior}}</pre>
Using HttpInterceptor Interface
The HttpInterceptor is an interface that is used for handling HTTP-specific errors, such as network issues, server errors, etc. It can intercept and modify HTTP requests or responses. Think of it as a service that can check and change the data going to and coming from a server.
To use an HttpInterceptor, create a class that implements the HttpInterceptor interface and define the intercept() method. This method takes an HTTP request and a handler, and it returns an observable of the HTTP event. Inside this method, you can modify the request or response as needed.
import{ Injectable }from'@angular/core';import{ HttpEvent, HttpInterceptor, HttpHandler, HttpRequest }from'@angular/common/http';import{ Observable }from'rxjs';import{ catchError }from'rxjs/operators';import{ throwError }from'rxjs'; @Injectable({ providedIn:'root'})exportclassErrorInterceptorimplementsHttpInterceptor{intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{return next.handle(req).pipe(catchError((error)=>{// Handle errorconsole.error('HTTP Error:', error);returnthrowError(error);}));}}</pre>
Using Try-Catch Blocks
In Angular, errors can occur during component lifecycle. To handle these errors, you can use the a try-catch block within the ngOnInit(), which is a component lifecycle hook defined by OnInit interface. It is important to implement this interface as it helps to check if component is properly initialized.
The try block is used to wrap the code that might throw an error during its execution. And, the catch block is used to handle any errors or exceptions that occur within the try block.
Here, you can see a component with try-catch block:
import{ Component, OnInit }from'@angular/core';import{ CommonModule }from'@angular/common'; @Component({ selector:'app-example', standalone:true, imports:[CommonModule], templateUrl:'./example.component.html', styleUrls:['./example.component.css']})exportclassExampleComponentimplementsOnInit{ngOnInit(){try{// code that might throw an errorthrownewError("Error message");}catch(error){console.error("error caught", error);}}}</pre>
Using Validation
Validation is used in Angular Forms to validate whether the user input is in the correct format or not before submission. The reactive forms and template-driven forms has built-in validators to handle validation errors.
With reactive forms, you can easily validate user input and display custom error messages as shown in the following code block −
import{ Component }from'@angular/core';import{ FormBuilder, FormGroup, Validators }from'@angular/forms';import{ CommonModule }from'@angular/common'; @Component({ selector:'app-registration', standalone:true, imports:[CommonModule], templateUrl:'./registration.component.html', styleUrls:['./registration.component.css']})exportclassRegistrationComponent{ registrationForm: FormGroup;constructor(private fb: FormBuilder){this.registrationForm =this.fb.group({username:['',[Validators.required, Validators.minLength(4)]], email:['',[Validators.required, Validators.email]],});}onSubmit(){if(this.registrationForm.invalid){this.showValidationErrors();return;}}privateshowValidationErrors(){ Object.keys(this.registrationForm.controls).forEach(control=>{const formControl =this.registrationForm.get(control);if(formControl?.invalid){ console.error(
${control} is invalid
);}});}}</pre>Print Page
Error Handling