Sub topic 12
Reporting unhandled errors with ErrorHandler
This chapter assumes you can write an Angular service that uses HttpClient, you know catchError and pipe(), and you have seen provideHttpClient in an application config. Earlier chapters handled errors close to the request. This chapter covers the last line of defense: errors that nothing else caught.
Why a global handler exists
catchError and interceptors handle the failures you expect. They cannot cover every failure:
- A template expression throws because a value is
undefined. - A click handler throws.
- A subscriber has no
errorcallback, so a rethrownHttpErrorResponsegoes unhandled. - A promise rejects and nobody awaits it.
Angular sends many of these to a single object, the ErrorHandler. It is a class with one method, handleError(error: unknown): void. The default implementation writes the error to console.error. Users never see that output, and you never receive it. Replacing the default lets you report errors to a logging service, show a generic notification, or both.
What reaches ErrorHandler
The exact set depends on your Angular version and on whether the app uses zone.js. These sources are the common ones:
| Source | Reaches ErrorHandler? |
|---|---|
| Error thrown in a template, lifecycle hook or event listener | Yes |
| Error thrown inside a signal `computed` or `effect` | Yes, when it surfaces during change detection or effect execution |
| Observable error with a subscriber that has no `error` callback | Usually. RxJS rethrows it asynchronously, and in a zone.js app the zone forwards it |
| Observable error handled by `catchError` that returns a fallback | No. The error stops there |
| Error caught in a `try/catch` that swallows it | No |
| Error inside code run with `NgZone.runOutsideAngular` | Not automatically. You must report it yourself |
The second-to-last row is the key one. The global handler only sees errors that your code failed to handle. If every catchError returns a fallback value, the global handler stays quiet even when requests fail. This is usually what you want, but only if those handlers log something themselves. A swallowed error is invisible to everyone.
The next diagram shows how an HTTP error moves through the layers you built in earlier chapters.
Writing a custom ErrorHandler
A custom handler is an injectable class that implements ErrorHandler. Keep the reporting logic in a separate service. That keeps the handler small and lets you replace the reporter in tests.
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ErrorReporter {
report(error: unknown, context: Record<string, unknown> = {}): void {
// Replace this body with a call to your logging service.
console.error('Reported error', error, context);
}
}
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
private reporter = inject(ErrorReporter);
handleError(error: unknown): void {
if (error instanceof HttpErrorResponse) {
const isNetworkError = error.status === 0;
const isServerError = error.status >= 500;
if (isNetworkError || isServerError) {
this.reporter.report(error, { url: error.url, status: error.status });
} else {
// 4xx responses are usually expected: validation, missing data, expired sessions.
console.warn(`Unhandled client error ${error.status} for ${error.url}`);
}
return;
}
this.reporter.report(error);
}
}The handler treats HttpErrorResponse differently from other errors. A TypeError from a template is a bug in your code and always deserves a report. A 404 that reached the global handler is usually not worth an alert, but you may still want a local warning so you can see it during development.
Registering the handler
Provide it under the ErrorHandler token in the application config, next to the HTTP providers.
import { ApplicationConfig, ErrorHandler } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { retryInterceptor } from './retry.interceptor';
import { GlobalErrorHandler } from './global-error-handler';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withInterceptors([retryInterceptor])),
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
],
};Use useClass, not useValue. With useClass, Angular constructs the handler inside the injection context, so inject() works in field initializers.
Gotchas
The handler is created early
Angular creates the ErrorHandler very early, before most of your application. If it injects a service that itself depends on something that can throw during startup, you can get a circular dependency or lose the original error. Two habits help:
- Inject only small, dependency-free services such as the
ErrorReporterabove. - For heavier dependencies, such as
Routeror a notification service backed by UI components, inject theInjectorand resolve the service lazily insidehandleError.
import { ErrorHandler, Injectable, Injector, inject } from '@angular/core';
import { NotificationService } from './notification.service';
@Injectable()
export class LazyGlobalErrorHandler implements ErrorHandler {
private injector = inject(Injector);
handleError(error: unknown): void {
console.error(error);
// Resolved on first use, after the application has finished starting.
this.injector.get(NotificationService).show('Something went wrong. Please try again.');
}
}The handler must never throw
If handleError throws, the error it throws is lost or can cause a loop of failures. Wrap any call that can fail, such as a network call to your logging service, in try/catch. Never use HttpClient inside the handler without care: if the logging request fails and the failure reaches the handler again, you can create an endless loop. Send reports with navigator.sendBeacon or a plain fetch wrapped in a catch, and leave HttpClient out of it.
Duplicate reports
An error rethrown from a service passes through several layers. If the service logs it, and the component logs it, and the global handler reports it, you get three entries for one failure. Pick one place to report each error. A workable rule is that services and interceptors translate errors and rethrow them, components show state to the user, and only the global handler reports.
Errors outside Angular's view
Code that runs outside Angular's zone, or errors that occur before the app bootstraps, do not reach the handler. In zone.js apps you can also call inject(ErrorHandler).handleError(error) yourself from such code. This is the supported way to route an error into the same pipeline. Recent Angular versions also offer provideBrowserGlobalErrorListeners(), which forwards the browser's error and unhandledrejection events to the ErrorHandler. Check your version's documentation before relying on it.
Testing the handler
Because the reporter is a separate service, the test replaces it with a spy and calls handleError directly. No HTTP mocking is needed.
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ErrorReporter, GlobalErrorHandler } from './global-error-handler';
describe('GlobalErrorHandler', () => {
let report: jasmine.Spy;
let handler: ErrorHandler;
beforeEach(() => {
report = jasmine.createSpy('report');
TestBed.configureTestingModule({
providers: [
{ provide: ErrorReporter, useValue: { report } },
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
],
});
handler = TestBed.inject(ErrorHandler);
});
it('reports 500 responses', () => {
handler.handleError(new HttpErrorResponse({ status: 500, url: '/api/users/1' }));
expect(report).toHaveBeenCalledTimes(1);
});
it('does not report 404 responses', () => {
spyOn(console, 'warn');
handler.handleError(new HttpErrorResponse({ status: 404, url: '/api/users/1' }));
expect(report).not.toHaveBeenCalled();
});
it('reports ordinary errors', () => {
handler.handleError(new TypeError('x is undefined'));
expect(report).toHaveBeenCalledTimes(1);
});
});Note that TestBed's own error handling is separate from this handler. Overriding the ErrorHandler token in a test is only useful when you want to assert on what the application reports.
Common mistakes
- Expecting every HTTP failure to arrive. A failure handled by
catchErrornever reaches the handler. - Swallowing errors to keep the console clean.
catchError(() => EMPTY)hides failures from every layer, including the global one. - Reporting 4xx responses as incidents. This floods your logging with expected validation and authorization responses. Classify before reporting.
- Using
HttpClientfor error reports. A failing report request can trigger another report. - Doing slow work in
handleError. The method is synchronous and called in the middle of Angular's work. Queue the report and return.
Exercise
A service method calls catchError(() => of([])) on a request that returns a 500 response. Will GlobalErrorHandler.handleError be called for that failure? What would you change if you want those failures reported while the user still sees an empty list?
Show answer
No. catchError returns a fallback value, so the observable completes normally and no error propagates to Angular. To keep the empty list and still report the failure, call the reporter inside catchError before returning the fallback. For example, catchError((error: HttpErrorResponse) => { reporter.report(error); return of([]); }). Alternatively, rethrow the error and let the component show an error state, which sends it on to the global handler when no error callback exists.
Exercise
Your GlobalErrorHandler injects Router in a field initializer, and the application fails at startup with a circular dependency error. Name one way to fix it.
Show answer
Inject Injector instead and resolve Router lazily inside handleError with this.injector.get(Router). The handler is created early, so deferring the lookup until an error occurs avoids the cycle.