angular
/

Angular Error Handling – Building Resilient Apps

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

angular

Angular Error Handling – Building Resilient Apps

The Importance of Error Resilience

In an enterprise environment, an unhandled exception can break the entire user experience. As a Technical Lead, your goal is to ensure that when things go wrong—whether it's a 500 Server Error from your Python backend or a runtime null pointer—the application fails gracefully. Angular provides multiple layers of defense, from local RxJS operators to a global 'Catch-All' mechanism.

  1. Handling API Errors with RxJS

Since Angular's HttpClient returns Observables, we use the catchError operator to intercept failed network requests. This allows you to log the specific error and return a fallback value or a user-friendly message to the component.

TypeScriptRead-only
1
import { catchError, throwError } from 'rxjs';

getProjects() {
  return this.http.get<Project[]>(this.apiUrl).pipe(
    catchError(error => {
      console.error('API Error:', error);
      // Return a user-friendly error message
      return throwError(() => new Error('Could not load projects. Please try again later.'));
    })
  );
}

  1. Global ErrorHandler (The Safety Net)

Angular provides a default ErrorHandler class that logs errors to the browser console. For professional apps like Revochamp, you should override this to send errors to a logging service (like Sentry) or show a global 'Something went wrong' UI notification.

TypeScriptRead-only
1
import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any): void {
    const message = error.message ? error.message : error.toString();
    
    // 1. Log to external monitoring service
    console.error('Global Error Captured:', message);

    // 2. Optionally redirect to an error page
    // window.location.href = '/error';
  }
}

  1. Centralized HTTP Error Interceptor

Instead of adding catchError to every single service, you can use a functional interceptor to handle common HTTP status codes (like 401 Unauthorized or 403 Forbidden) in one place.

TypeScriptRead-only
1
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status === 401) {
        // Logic to logout or refresh token
      }
      return throwError(() => error);
    })
  );
};

Error Handling Strategy Comparison

StrategyLevelBest Use Case
Try-CatchLocal / MethodSynchronous logic (JSON parsing, Math)
catchError OperatorService / APINetwork failures & data transformation
HttpInterceptorGlobal NetworkAuth failures (401), Server timeouts
Global ErrorHandlerApp-wideUnexpected runtime crashes & tracking

Test Your Knowledge

Q1
of 3

Which RxJS operator is used to handle errors in an Observable stream?

A
map
B
filter
C
catchError
D
tap
Q2
of 3

Which interface do you implement to create a custom global error handler?

A
ErrorListener
B
ErrorHandler
C
HttpInterceptor
D
AppErrorHandler
Q3
of 3

Which HTTP status code typically indicates that a user is unauthorized and might need a redirect?

A
404
B
500
C
401
D
200

Frequently Asked Questions

Should I use try-catch with HttpClient?

No. HttpClient is asynchronous and uses Observables. A try-catch block will not catch errors from an Observable stream. You must use the 'catchError' operator within the '.pipe()' method.

How do I show an error message to the user?

The best practice is to have the service 'throw' the error. The component then subscribes to the service and uses the 'error' callback of the '.subscribe()' method to set a local 'errorMessage' variable displayed in the HTML template.

What is HttpErrorResponse?

It is a specialized class in Angular that provides detailed information about a failed HTTP request, including the status code (e.g., 404), the status text, and the error body returned by the server.

Previous

angular interceptors

Next

angular lifecycle hooks

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.