Angular Error Handling

Learn Angular Error Handling with HttpClient, RxJS catchError, retry, global ErrorHandler, HTTP Interceptors, user-friendly error messages, enterprise architecture, best practices, and interview questions.

Error handling is one of the most critical aspects of enterprise Angular applications.

Applications must gracefully handle:

  • HTTP Errors
  • Network Failures
  • Validation Errors
  • Runtime Exceptions
  • Authentication Failures
  • Server Errors
  • Timeout Errors
  • Unexpected Exceptions

A good error handling strategy improves reliability, user experience, debugging, and system stability.

Angular provides several mechanisms for handling errors, including:

  • RxJS Operators
  • HTTP Interceptors
  • Global ErrorHandler
  • Route Error Handling
  • Form Validation
  • Async Error Handling

Error Handling is one of the most frequently asked Angular interview topics.


Table of Contents

  • What is Error Handling?
  • Why Error Handling Matters
  • Types of Errors
  • Error Handling Architecture
  • Handling HTTP Errors
  • RxJS catchError()
  • Retry Strategy
  • Global ErrorHandler
  • HTTP Interceptors
  • User-Friendly Error Messages
  • Enterprise Banking Example
  • Performance Best Practices
  • Common Mistakes
  • Top 10 Interview Questions
  • Summary

What is Error Handling?

Error Handling is the process of detecting, managing, logging, and recovering from application failures without crashing the application.

Instead of displaying raw exceptions to users, applications should:

  • Show meaningful messages
  • Log technical details
  • Recover whenever possible
  • Maintain application stability

Types of Errors

Error Type Example
HTTP Errors 404, 500
Network Errors Internet disconnected
Validation Errors Invalid email
Runtime Errors Undefined object access
Authentication Errors 401 Unauthorized
Authorization Errors 403 Forbidden
Timeout Errors Server timeout
JavaScript Errors Unexpected exception

Error Handling Architecture

flowchart TD

User

User --> Component

Component --> Service

Service --> HttpClient

HttpClient --> RESTAPI

RESTAPI --> Error

Error --> Interceptor

Interceptor --> GlobalErrorHandler

GlobalErrorHandler --> Logger

Logger --> Monitoring

GlobalErrorHandler --> UserMessage

Why Error Handling Matters

Without Error Handling

  • Application crashes
  • Poor user experience
  • Difficult debugging
  • Lost data
  • Security risks

With Proper Error Handling

  • Better reliability
  • Easier maintenance
  • Better monitoring
  • Cleaner logs
  • Improved customer satisfaction

HTTP Error Categories

Status Meaning
400 Bad Request
401 Unauthorized
403 Forbidden
404 Resource Not Found
409 Conflict
422 Validation Failed
429 Too Many Requests
500 Internal Server Error
503 Service Unavailable

Handling HTTP Errors with catchError()

import {
  catchError
} from 'rxjs/operators';

import {
  throwError
} from 'rxjs';

getUsers() {

  return this.http
    .get<User[]>(this.api)
    .pipe(

      catchError(error => {

        console.error(error);

        return throwError(
          () => error
        );

      })

    );

}

catchError() allows you to transform, log, or recover from errors before passing them to subscribers.


HTTP Error Flow

flowchart LR

HttpClient

HttpClient --> RESTAPI

RESTAPI --> Success

RESTAPI --> Error

Error --> catchError

catchError --> Component

Handling Errors in Components

this.userService
  .getUsers()
  .subscribe({

    next: users => {

      this.users = users;

    },

    error: error => {

      this.errorMessage =
        'Unable to load users.';

    }

  });

The component should display a user-friendly message instead of exposing technical details.


Component Error Flow

sequenceDiagram

participant Component

participant Service

participant API

Component->>Service: Request

Service->>API: GET

API-->>Service: Error

Service-->>Component: Error

Component-->>User: Friendly Message

Retry Failed Requests

Retry temporary failures.

import {
  retry
} from 'rxjs/operators';

this.http
  .get(this.api)
  .pipe(

    retry(2)

  );

Use retry only for temporary failures such as:

  • Network interruptions
  • Temporary server overload
  • Timeout issues

Avoid retrying permanent client errors such as:

  • 400
  • 401
  • 403
  • 404

Retry Architecture

flowchart TD

Request

Request --> Failure

Failure --> Retry

Retry --> API

API --> Success

HTTP Interceptor for Global Errors

return next(req)
.pipe(

catchError(error=>{

console.error(error);

return throwError(

()=>error

);

})

);

Benefits

  • Centralized error handling
  • Reusable logic
  • Cleaner services
  • Consistent behavior

Global Error Flow

flowchart LR

Request

Request --> Interceptor

Interceptor --> API

API --> Error

Error --> Interceptor

Interceptor --> UI

Global ErrorHandler

Angular provides a global ErrorHandler service for handling uncaught runtime exceptions.

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

@Injectable()
export class GlobalErrorHandler
implements ErrorHandler {

  handleError(
    error: any
  ): void {

    console.error(
      'Application Error',
      error
    );

  }

}

Register

providers: [

{

provide:ErrorHandler,

useClass:GlobalErrorHandler

}

]

This is useful for logging unexpected application errors to monitoring platforms.


Global ErrorHandler Architecture

flowchart TD

Application

Application --> RuntimeException

RuntimeException --> ErrorHandler

ErrorHandler --> Logger

Logger --> Monitoring

User-Friendly Error Messages

Avoid

TypeError:
Cannot read property...

Better

Something went wrong.

Please try again later.

Examples

Error User Message
404 Requested data was not found.
401 Please sign in to continue.
403 You do not have permission to perform this action.
500 Something went wrong. Please try again later.
Network Please check your internet connection.

Logging Errors

Applications should log:

  • URL
  • HTTP Method
  • Status Code
  • Timestamp
  • User ID (if appropriate)
  • Correlation ID
  • Stack Trace
  • Browser Information

Logging can be sent to monitoring platforms such as Splunk, ELK, Datadog, or cloud monitoring solutions.


Error Logging Flow

flowchart TD

Application

Application --> Logger

Logger --> Monitoring

Monitoring --> Dashboard

Dashboard --> SupportTeam

Enterprise Banking Example

Money Transfer Application

Possible Errors

  • Invalid Account
  • Insufficient Balance
  • Authentication Failure
  • Server Timeout
  • Payment Gateway Failure
  • Network Disconnection

Architecture

flowchart TD

Customer

Customer --> AngularApp

AngularApp --> TransferService

TransferService --> HttpClient

HttpClient --> ErrorInterceptor

ErrorInterceptor --> BankingAPI

BankingAPI --> CoreBanking

CoreBanking --> Response

Response --> ErrorInterceptor

ErrorInterceptor --> Logger

Logger --> Monitoring

ErrorInterceptor --> UserMessage

Benefits

  • Centralized logging
  • Better reliability
  • Improved customer experience
  • Easier production support
  • Faster issue diagnosis

Error Handling Strategy

flowchart TD

Error

Error --> HTTP

Error --> Runtime

Error --> Validation

HTTP --> Interceptor

Runtime --> ErrorHandler

Validation --> FormValidator

Interceptor --> Logger

ErrorHandler --> Logger

FormValidator --> User

Performance Best Practices

Practice Benefit
Handle errors centrally Less duplicate code
Retry only temporary failures Avoid unnecessary traffic
Log unexpected errors Better debugging
Display friendly messages Better user experience
Keep stack traces out of the UI Better security
Use monitoring tools Faster issue detection
Categorize errors Easier troubleshooting

Common Mistakes

Ignoring Errors

Bad

.subscribe();

Always provide an error handling strategy.


Showing Raw Exceptions

Avoid displaying stack traces or internal error messages to end users.


Retrying Every Error

Do not retry:

  • 400
  • 401
  • 403
  • 404

Retry only temporary failures.


Logging Sensitive Information

Avoid logging:

  • Passwords
  • Tokens
  • Personal information
  • Financial data

Mask or omit sensitive values before logging.


Duplicating Error Handling

Centralize common logic using HTTP Interceptors and the Global ErrorHandler.


Best Practices

  • Use catchError() for request-specific handling.
  • Use HTTP Interceptors for global HTTP errors.
  • Use ErrorHandler for uncaught runtime exceptions.
  • Display user-friendly error messages.
  • Log errors to centralized monitoring systems.
  • Retry only transient failures.
  • Protect sensitive information in logs.
  • Keep error handling consistent across the application.
  • Test failure scenarios.
  • Document error codes and expected behavior.

Advantages

Feature Benefit
catchError() Reactive error handling
HTTP Interceptors Centralized HTTP errors
Global ErrorHandler Application-wide exception handling
Logging Easier debugging
Friendly Messages Better UX
Monitoring Faster production support
Retry Better resilience
Enterprise Ready Production-grade reliability

Top 10 Angular Error Handling Interview Questions

1. What is Error Handling in Angular?

Answer

Error handling is the process of detecting, managing, logging, and recovering from application failures while providing a stable user experience.


2. Which RxJS operator is commonly used for HTTP error handling?

Answer

catchError() is the primary RxJS operator used to intercept and handle HTTP errors.


3. What is the purpose of Angular's Global ErrorHandler?

Answer

The ErrorHandler service captures uncaught runtime exceptions, allowing applications to log and monitor unexpected failures.


4. Why should HTTP Interceptors be used for error handling?

Answer

They centralize HTTP error handling, reduce duplicate code, and ensure consistent behavior across all API requests.


5. When should retry() be used?

Answer

Use retry() only for transient failures such as temporary network issues or short-lived server problems—not for permanent client errors like 400 or 404.


6. Why shouldn't raw exceptions be shown to users?

Answer

Raw exceptions expose technical details, confuse users, and may reveal sensitive implementation information.


7. What information should be logged?

Answer

  • Request URL
  • HTTP method
  • Status code
  • Timestamp
  • Stack trace
  • Correlation ID
  • User context (when appropriate and privacy-compliant)

8. What are common HTTP error codes?

Answer

  • 400 Bad Request
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 409 Conflict
  • 500 Internal Server Error
  • 503 Service Unavailable

9. What are Angular Error Handling best practices?

Answer

  • Use catchError()
  • Use HTTP Interceptors
  • Use Global ErrorHandler
  • Display friendly messages
  • Log errors securely
  • Retry only transient failures
  • Monitor production systems

10. Why is centralized error handling important?

Answer

Centralized error handling improves maintainability, provides consistent behavior, simplifies debugging, and enhances application reliability.


Interview Cheat Sheet

Topic Remember
HTTP Errors catchError()
Retry retry()
Global Runtime Errors ErrorHandler
HTTP Errors Interceptor
Friendly Messages Never expose stack traces
Logging URL, status, timestamp
Monitoring Splunk, ELK, Datadog
Retry Policy Only transient failures
Security Never log sensitive data
Best Practice Centralize error handling

Summary

Angular provides a comprehensive error handling ecosystem through RxJS operators, HTTP Interceptors, and the Global ErrorHandler service. By combining request-level handling with centralized logging, user-friendly messaging, secure monitoring, and carefully designed retry strategies, developers can build reliable, maintainable, and production-ready enterprise applications that gracefully recover from failures without compromising user experience or security.


Key Takeaways

  • ✔ Error handling is essential for enterprise Angular applications.
  • ✔ Use catchError() for request-level error handling.
  • ✔ Use HTTP Interceptors for centralized HTTP error management.
  • ✔ Use ErrorHandler for uncaught runtime exceptions.
  • ✔ Retry only transient failures.
  • ✔ Display meaningful messages instead of raw exceptions.
  • ✔ Log errors securely and consistently.
  • ✔ Never expose sensitive information in logs or UI.
  • ✔ Monitor production errors using centralized logging tools.
  • ✔ Error Handling is one of the most important Angular interview topics.

Next Article

➡️ 65-RxJS-Observables-QA.md