Friday, 18 April 2025

Angular 19 | Chapter 11 | Runtime Error Handling in Angular Application

 

How to handle runtime errors in Angular ?

🔥Handling application errors in Angular is key to building robust and user-friendly apps. There are multiple layers where errors can occur (HTTP calls, forms, components, services, etc.), and Angular provides powerful ways to handle them gracefully.

 

🛠️ Levels of Error Handling in Angular

Level

Examples

Tool(s) to Use

Component

Runtime errors in logic

try/catch, guards

Services (HTTP/API)

API failures, invalid responses

RxJS catchError, interceptors

Global (App-wide)

Unhandled app-level errors

ErrorHandler class

Forms

Invalid user input

Form validation & control errors

Routing

Wrong route, access denied

Route Guards, wildcard routes (**)

 

1. Handling HTTP Errors with catchError

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

getUser(id: number): Observable<User> {
  return this.http.get<User>(`/api/users/${id}`).pipe(
    catchError(error => {
      console.error('Error fetching user:', error);
      return throwError(() => new Error('Something went wrong!'));
    })
  );
}

You can also show a toast or message to the user inside catchError.

 

2. Global Error Handling with ErrorHandler

Create a custom error handler:

import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any): void {
    console.error('Global Error:', error);
    // Log to external server, show user message, etc.
    alert('Oops! Something broke.');
  }
}

Register it in app.module.ts:

providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }]


 

 

3. HTTP Interceptor for Centralized Error Handling

Create an interceptor to catch all HTTP errors:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        console.error('HTTP Error:', error);
        alert('Server error occurred');
        return throwError(() => error);
      })
    );
  }
}

Register it:

providers: [
  { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
]

 

4. Error Handling in Forms

Check and display error messages like this:

<input formControlName="email" />
<div *ngIf="form.get('email')?.errors?.['required']">
  Email is required.
</div>
<div *ngIf="form.get('email')?.errors?.['email']">
  Invalid email format.
</div>

 

5. Routing Errors (Wildcard Routes, Guards)

Catch unknown routes:

{ path: '**', component: NotFoundComponent }

Add route guards to block access or redirect:

{ path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }

 

6. Try-Catch for Logic or Template Errors

try {
  // risky logic
} catch (err) {
  console.error('Caught error:', err);
}

 

Bonus: Logging Service

Use a logging service to log to console, a server, or local storage:

@Injectable({ providedIn: 'root' })
export class LoggerService {
  logError(error: any) {
    console.error('[LOGGED ERROR]', error);
    // Send to backend API or tracking tool
  }
}

 

🧠 Summary

Where?

How?

HTTP

catchError, Interceptors

Global

Custom ErrorHandler

Forms

Validation + template messages

Routing

Guards + Wildcard routes

General

try/catch, Logging service

 

No comments:

Post a Comment