Angular Academy · Lesson

Handling Errors Globally

Catch and transform HTTP errors centrally.

Lesson 3 of 413 steps

Handling Errors Globally is a free Angular Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Angular Academy learning path, and your progress syncs across the web and the CoddyKit app. The Angular Academy course includes 4 lessons in total.

Central error handling

Instead of catching HTTP errors in every component, an interceptor can handle them globally: log them, show a toast, redirect on 401, or normalize the error shape.

catchError in an interceptor

Pipe the next(req) stream through catchError to intercept failures.

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

export const errorInterceptor: HttpInterceptorFn = (req, next) =>
  next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      console.error('HTTP error', err.status);
      return throwError(() => err);
    })
  );

Inspecting HttpErrorResponse

HttpErrorResponse carries status, message, and the server error body. Branch on status to handle different cases.

catchError((err: HttpErrorResponse) => {
  if (err.status === 0) console.error('network/CORS error');
  else console.error('server error', err.status);
  return throwError(() => err);
})

Redirect on 401

A 401 usually means the session expired. Redirect to login from the interceptor.

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const router = inject(Router);
  return next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      if (err.status === 401) router.navigate(['/login']);
      return throwError(() => err);
    })
  );
};

Showing a notification

Inject a toast/notification service to surface errors to the user consistently.

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const toast = inject(ToastService);
  return next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      toast.error(err.error?.message ?? 'Something went wrong');
      return throwError(() => err);
    })
  );
};

Re-throw vs swallow

Usually re-throw with throwError(() => err) so components can still react. Only return a fallback observable (like of(null)) when you truly want to hide the error from callers.

Normalizing the error

Map varied server error bodies into a consistent app error shape before re-throwing, simplifying downstream handling.

catchError((err: HttpErrorResponse) => {
  const appError = {
    code: err.status,
    message: err.error?.message ?? err.message
  };
  return throwError(() => appError);
})

Distinguishing client vs server errors

err.error instanceof ErrorEvent (or err.status === 0) indicates a client/network error; otherwise the backend returned an error status. Handle them differently.

Avoid double handling

If the interceptor already shows a toast, components should not also show one for the same error. Decide on one layer of user-facing handling to avoid duplicate messages.

Logging to a monitoring service

A central interceptor is the ideal place to forward errors to a monitoring tool (Sentry, etc.) with the request context attached.

export const errorInterceptor: HttpInterceptorFn = (req, next) => {
  const monitor = inject(MonitoringService);
  return next(req).pipe(
    catchError((err: HttpErrorResponse) => {
      monitor.captureHttpError(req.url, err.status, err.message);
      return throwError(() => err);
    })
  );
};

Ordering the error interceptor

Place the error interceptor so it wraps the others, letting it catch errors from the whole chain (including retries).

provideHttpClient(
  withInterceptors([authInterceptor, retryInterceptor, errorInterceptor])
)

Quick Check

Test your understanding of global error handling.

Recap: Handling Errors Globally

An error interceptor centralizes HTTP failure handling.

  • Use catchError on next(req).
  • Branch on HttpErrorResponse.status (e.g. 401 redirect).
  • Re-throw to let components react; swallow only when intended.

Next: retry and loading indicators.

Free to start

Learn HTML with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
38
Lessons
144

Frequently Asked Questions

Is the “Handling Errors Globally” lesson free?

Yes — any 3 lessons of the Angular Academy learning path, including “Handling Errors Globally”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Angular Academy course includes 4 lessons in total.

What will I learn in “Handling Errors Globally”?

Catch and transform HTTP errors centrally. You practise Angular Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Angular Academy?

No prior experience is required. Angular Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Handling Errors Globally” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Angular Academy lesson?

Yes. Every Angular Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Functional Interceptors
  2. Adding Auth Headers
  3. Handling Errors Globally
  4. Retry and Loading Indicators
← Back to Angular Academy