WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Intermediate · question 36 of 100

How do you handle error handling and reporting in Angular applications?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

Error handling and reporting in Angular applications are essential for diagnosing and resolving problems that might occur during the application’s runtime. In Angular, there are several tools and techniques we can use to handle errors effectively. Some of the common techniques are:

1. **Error handling in Reactive forms:**

In Angular Reactive forms, you can define form controls, validators, and error messages to display when a specific control doesn’t meet the validation criteria. To handle errors in Reactive forms, follow these steps:

a. Define form controls and validators:

Create a new instance of the FormGroup that includes form controls with their validation rules using the FormControl class and adding custom validation rules using the Validators class.

Example:

import { FormGroup, FormControl, Validators } from '@angular/forms';

this.form = new FormGroup({
  username: new FormControl('', [Validators.required, Validators.minLength(3)]),
  password: new FormControl('', [Validators.required, Validators.minLength(6)]),
});

b. Display error messages for invalid form fields:

In the template file, add the necessary markup to display the error messages depending on whether the form field is valid or not. Use the ‘*ngIf‘ directive to conditionally display error messages.

Example:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <div>
    <label for="username">Username</label>
    <input id="username" type="text" formControlName="username">
    <div *ngIf="form.get('username').invalid && form.get('username').touched">
      <span *ngIf="form.get('username').errors.required">Username is required.</span>
      <span *ngIf="form.get('username').errors.minlength">Username must be at least 3 characters long.</span>
    </div>
  </div>
  <!-- ... -->
</form>

2. **Error handling in Http requests:** Angular HTTP requests can throw errors due to various reasons, such as network issues, wrong URLs, or server errors. The most common way to handle HTTP errors is through the use of ‘catchError‘ and ‘throwError‘ RxJS operators in combination with the ‘pipe‘ method.

Example:

import { HttpClient } from '@angular/common/http';
import { catchError, throwError } from 'rxjs/operators';

this.http.get('https://api.example.com/data').pipe(
  catchError(error => {
    console.error('Error occurred:', error);
    return throwError(error);
  })
).subscribe(
  data => console.log('Data received:', data),
  error => console.log('Error received:', error)
);

This will catch any errors that may occur during the HTTP request and log them to the console.

3. **Global error handling:**

In Angular, you can create a global error handler by implementing the ‘ErrorHandler‘ class and overriding its ‘handleError‘ method. This will catch any unhandled errors in the application.

To create a global error handler follow these steps:

a. Create the global error handler provider:

import { ErrorHandler } from '@angular/core';
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any): void {
    console.error('An error occurred: ', error);
    // Send the error to an external logging service, display a notification, etc.
  }
}

b. Add the global error handler to the ‘providers‘ array in the AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { AppComponent } from './app.component';
import { GlobalErrorHandler } from './global-error-handler';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    { provide: ErrorHandler, useClass: GlobalErrorHandler }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, any unhandled errors will be caught by the GlobalErrorHandler and can be handled accordingly.

4. **Error reporting services:**

In addition to the above methods, you might consider using an external error reporting service like Sentry, Rollbar, or LogRocket to track and manage errors in your Angular application. These services provide an SDK that can be integrated into the Angular application and automatically report errors to their respective platforms.

To conclude, error handling and reporting are crucial aspects of Angular applications to ensure a smooth user experience and to identify and fix any issues that may arise during runtime. By using the techniques and tools mentioned above, you can effectively handle and report errors in Angular applications.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics