Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 74 ยท HTTP and RxJS

Error Handling: ErrorHandler and HTTP Errors

Handle errors in Angular properly with a custom ErrorHandler, an HTTP error interceptor, retries for safe requests, a logging service and a friendly error message for users.

Every app fails sometimes: the network drops, the server returns a 500, a template reads a property of undefined. What matters is what the user sees and what you learn. A blank screen and a silent console error is the worst outcome; a clear message for the user and a logged, searchable report for you is the goal.

Angular gives you two global places to catch problems. The ErrorHandler receives every error that nothing else handled. An HTTP interceptor sees every failed request before your component does. This lesson combines them with a small logging service and a user-facing message. You should know HttpClient and Interceptors.

Real versus stand-in. The typescript blocks are real Angular code to read. The runnable examples are stand-ins in plain TypeScript: a function that classifies HTTP failures the way the interceptor does, and a pipeline with a fake request, a retry rule and a fake ErrorHandler, all deterministic.

The three kinds of error

Kind Example Where to handle it
Expected failures A form is invalid; the user is not allowed to open a page; a search returned nothing Locally, in the component or service, with normal control flow
HTTP failures 404, 401, 500, no network In the call that needs a fallback, plus one interceptor for the common rules
Unexpected bugs TypeError in a template, a thrown error in an event handler The global ErrorHandler

Do not use the global handler for the first kind, and do not leave the third kind unhandled. Each level should deal with what it understands and let the rest travel upward.

A custom ErrorHandler

Angular's default ErrorHandler logs to the console. Replace it by providing your own class under the same token. Its single method, handleError(error), receives errors from event handlers, the template, lifecycle hooks, and promises Angular knows about.

TypeScript
// logger.ts
import { Injectable } from '@angular/core';

export interface ErrorReport {
  message: string;
  stack?: string;
  url: string;
  time: string;
}

@Injectable({ providedIn: 'root' })
export class Logger {
  error(error: unknown): void {
    const report: ErrorReport = {
      message: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
      url: location.href,
      time: new Date().toISOString(),
    };
    console.error(report);
    // In production, send it to your own endpoint or a monitoring service.
    navigator.sendBeacon?.('/api/log', JSON.stringify(report));
  }
}
TypeScript
// global-error-handler.ts
import { ErrorHandler, inject, Injectable } from '@angular/core';
import { Logger } from './logger';
import { Notifications } from './notifications';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private readonly logger = inject(Logger);
  private readonly notifications = inject(Notifications);

  handleError(error: unknown): void {
    this.logger.error(error);
    this.notifications.show('Something went wrong. Please try again.');
  }
}
TypeScript
// app.config.ts
import { ApplicationConfig, ErrorHandler, provideBrowserGlobalErrorListeners } from '@angular/core';

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    { provide: ErrorHandler, useClass: GlobalErrorHandler },
  ],
};

provideBrowserGlobalErrorListeners() (in recent versions of new projects) also routes the browser's error and unhandledrejection events into the handler, so errors from timers or unawaited promises are not lost. Check that it is present in your version's generated app.config.ts.

Never show error.message of an unexpected error to the user: it can contain internal details and is rarely helpful. Show a short, friendly message, and keep the details in the log. Also avoid throwing inside handleError itself, because an error in the handler has nowhere left to go.

Server-side rendering. Errors on the server go to the same handler, but location and navigator do not exist there. Guard browser-only calls (SSR and Hydration) or send server errors to a different logger.

Turning an HTTP failure into something useful

HttpClient reports failures as an HttpErrorResponse with a status. A status of 0 means the request never completed (offline, CORS, DNS, timeout). Statuses from 400 up are answers from a server. A good user message depends on which one it is:

TypeScript
// http-error-message.ts
import { HttpErrorResponse } from '@angular/common/http';

export function describeHttpError(error: HttpErrorResponse): string {
  if (error.status === 0) return 'You seem to be offline. Check your connection and try again.';
  if (error.status === 401) return 'Please sign in again.';
  if (error.status === 403) return 'You do not have permission to do that.';
  if (error.status === 404) return 'We could not find what you asked for.';
  if (error.status === 429) return 'Too many requests. Wait a moment and retry.';
  if (error.status >= 500) return 'The server had a problem. We have been notified.';
  return 'The request could not be completed.';
}

An error interceptor with safe retries

An interceptor is the right place for rules that apply to every request. This one retries only GET requests and only for network failures or 5xx answers, with a short delay. Retrying a POST can create duplicate orders, so never retry unsafe methods blindly. After the retries it logs the error, shows a message, and rethrows, so the component that asked can still react (for example by showing its own empty state).

TypeScript
// error.interceptor.ts
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, retry, throwError, timer } from 'rxjs';
import { Logger } from './logger';
import { Notifications } from './notifications';
import { describeHttpError } from './http-error-message';

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const logger = inject(Logger);
  const notifications = inject(Notifications);

  const retryable = req.method === 'GET';

  return next(req).pipe(
    retry({
      count: retryable ? 2 : 0,
      delay: (error: HttpErrorResponse, attempt) =>
        error.status === 0 || error.status >= 500
          ? timer(300 * 2 ** (attempt - 1)) // 300 ms, then 600 ms
          : throwError(() => error),         // do not retry 4xx answers
    }),
    catchError((error: HttpErrorResponse) => {
      logger.error(error);
      if (error.status !== 401) {
        notifications.show(describeHttpError(error));
      }
      return throwError(() => error);
    }),
  );
};

Register it with provideHttpClient(withInterceptors([errorInterceptor])). A 401 is skipped here because an authentication interceptor usually handles it by refreshing a token or redirecting to the login page. Order matters: interceptors run in the order you list them, so put the one that adds headers before the one that reports errors (Interceptors).

Showing the message

The Notifications service is a plain signal store, like those in State Management. One component near the root of the app shows it:

TypeScript
@Injectable({ providedIn: 'root' })
export class Notifications {
  readonly message = signal<string | null>(null);
  show(text: string): void { this.message.set(text); }
  clear(): void { this.message.set(null); }
}

@Component({
  selector: 'app-toast',
  template: `
    @if (notifications.message(); as text) {
      <div role="alert" class="toast">
        {{ text }}
        <button type="button" (click)="notifications.clear()">Dismiss</button>
      </div>
    }
  `,
})
export class Toast {
  protected readonly notifications = inject(Notifications);
}

role="alert" makes a screen reader announce the message when it appears (Security and Accessibility).

Stand-in 1: classify the failure

The first stand-in contains the decision logic as plain functions, so you can see which statuses are retried and which message each gets.

TypeScript A stand-in: retry rules and messages by status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice that a failed POST is never retried, even for a 500, and that a 404 is not retried because asking again gets the same answer.

Stand-in 2: the whole pipeline

The second stand-in wires everything together: a fake server that fails twice and then succeeds, an interceptor-style withRetry, a fake ErrorHandler that logs and shows a message for an unexpected bug, and a component-level try/catch for an expected failure.

TypeScript A stand-in: retry, global handler and user message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Case 1 shows the interceptor's value: the component never sees the two transient failures. Case 2 shows an error that is rethrown to the caller. Case 3 shows the safety net for everything nobody expected.

Practical advice

  • Log once. If the interceptor logs an HTTP error and the component rethrows it into ErrorHandler, you will see it twice. Decide which layer owns logging.
  • Add context. A report needs the URL, the user's action and a release number, not only a stack trace. Source maps let you read minified stacks.
  • Do not swallow errors. An empty catch {} hides bugs. At least log.
  • Test the unhappy paths. In unit tests, respond with HttpTestingController.expectOne(...).flush('', { status: 500, statusText: 'Server Error' }) (Testing).
  • Offer a way out. A message with a Retry button beats a message alone.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a custom ErrorHandler receive?

    ErrorHandler is the last safety net for unhandled errors. Expected failures like validation or a missing search result belong in the code that knows how to handle them.
  2. 2. What does HttpErrorResponse.status equal when the request never reached a server, for example offline?

    Status 0 means no HTTP response was received at all. Offline, DNS failures, CORS problems and timeouts commonly give 0.
  3. 3. Why should an error interceptor retry only GET requests?

    GET requests are safe to repeat. Retrying a non-idempotent request such as POST can run the same operation twice.
  4. 4. After the interceptor logs and shows a message, why does it rethrow the error?

    Rethrowing keeps the error flowing to the caller, which may want to show an empty state or a Retry button. Swallowing it would make the failed call look like it succeeded.

Summary

  • Handle expected failures locally, HTTP failures in an interceptor, and unexpected bugs in a custom ErrorHandler provided with { provide: ErrorHandler, useClass: ... }.
  • HttpErrorResponse.status of 0 means no response arrived; show different messages for offline, 4xx and 5xx.
  • Retry only safe requests (GET) and only transient failures, with a growing delay.
  • Log the detail for developers, and show a short friendly message with role="alert" to users.
  • Rethrow errors from interceptors so callers can still react, and log in exactly one layer.

Next: read the response safely and turn streams into signals in Signals and RxJS Interop.