Sub topic 11
Handling errors without zones
This chapter assumes you can build standalone components, you know what ErrorHandler is, and you have already enabled zoneless mode with provideZonelessChangeDetection(). It covers where errors go once Zone.js is gone, which ones Angular never sees, and how to test error paths.
How zones reported errors
In a zone-based app, Zone.js patches setTimeout, promises, event listeners and similar APIs. Angular runs your code inside its own zone, NgZone. Any error that escapes from code running in that zone is emitted on NgZone.onError. ApplicationRef subscribes to that stream and forwards each error to the application's ErrorHandler. The default ErrorHandler logs to the console.
This meant that most errors reached ErrorHandler without you doing anything. A throw inside a setTimeout callback, a rejected promise, or an RxJS callback was reported, because the zone had wrapped all of it.
Without Zone.js there is no patched setTimeout and no zone wrapping your callbacks. In zoneless mode, NgZone is replaced by a no-op implementation, and NgZone.onError never emits. Code that subscribed to it to report errors silently stops reporting.
Errors Angular still catches
Angular does not stop catching errors in code it runs itself. In a zoneless app, these paths still call ErrorHandler.handleError():
- Event listeners declared in templates, such as
(click)="save()". - Errors thrown while Angular renders a view during change detection.
- Errors thrown inside
effect()callbacks. - Errors from lifecycle hooks, because Angular calls them.
- Errors that happen while the router runs navigation.
Angular wraps each of these in its own try/catch. That is why they work without a zone.
Errors Angular no longer sees by default
Code that Angular did not call, and that fails later, is a different case. Examples are a setTimeout callback, a rejected promise nobody awaits, or a subscribe() with no error callback. Zone.js used to intercept these. Now the browser handles them. The browser fires a global error event for uncaught exceptions and an unhandledrejection event for unhandled promise rejections. Without a listener, they appear in the console and Angular's ErrorHandler never hears about them.
Your logging service would therefore miss them.
Global error listeners
Angular provides a function to close this gap: provideBrowserGlobalErrorListeners(). It registers listeners for the window error and unhandledrejection events and forwards each one to ErrorHandler. New projects generated with recent Angular CLI versions include it in app.config.ts.
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
],
};If you migrate an older app and your app.config.ts lacks this provider, add it. It restores what the zone gave you for free: one place where uncaught errors from timers and promises arrive.
The diagram shows the paths.
The first three paths work without any setup. The bottom two need provideBrowserGlobalErrorListeners().
RxJS errors
RxJS adds one more case. If you call subscribe(next) and the stream errors, and you gave no error callback, RxJS reports the error through a deferred throw. That throw becomes a global error event. So with the global listeners installed, it still reaches ErrorHandler. Without them, it only reaches the console.
Still, prefer handling stream errors where they happen. Use catchError or an error callback when you can recover, for example by showing a message or a fallback value. Treat the global handler as the last line of defense, not as control flow.
The async pipe and toSignal() behave differently. If an observable bound with async errors, the pipe throws during rendering, and Angular reports it. If toSignal() receives an error, reading the signal rethrows the error, and the place that reads it reports it. Pass initialValue and wrap the source in catchError if you want a fallback.
Writing a custom ErrorHandler
Replace the default by providing your own class for the ErrorHandler token. The class below sends the error to a logging service and also writes it to the console.
import { ErrorHandler, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ErrorLogger {
log(error: unknown): void {
console.info('Would send to a logging backend:', error);
}
}
@Injectable()
export class AppErrorHandler implements ErrorHandler {
private readonly logger = inject(ErrorLogger);
handleError(error: unknown): void {
this.logger.log(error);
console.error(error);
}
}Register it next to the other providers.
import { ApplicationConfig, ErrorHandler, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import { AppErrorHandler } from './app-error-handler';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
{ provide: ErrorHandler, useClass: AppErrorHandler },
],
};Keep handleError simple and free of exceptions. If the handler throws, you lose the original error and may create a loop. Do not rely on it to update the UI. If you want to show an error banner, write the message to a signal in a service. Signals schedule change detection in zoneless mode, so the banner appears.
Reporting errors yourself
Sometimes you catch an error and still want it logged. Inject ErrorHandler and call it directly.
import { ErrorHandler, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ProfileLoader {
private readonly errorHandler = inject(ErrorHandler);
async load(url: string): Promise<unknown | null> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return await response.json();
} catch (error) {
this.errorHandler.handleError(error);
return null;
}
}
}This goes through the same path as every other error, so a custom handler sees it too.
Server rendering
On the server there is no browser window, so the browser global listeners do not apply. An uncaught error in a timer or promise during server rendering can end up in the Node.js process rather than in ErrorHandler. Handle errors in server-side code explicitly with try/catch and catchError. If you use asynchronous work during rendering, wrap it in PendingTasks.run(), as the earlier chapter on pending tasks describes. That way a failure rejects a task Angular is tracking instead of happening after the page was serialized.
Testing error paths
In zoneless tests, TestBed installs an error handler that rethrows application errors. This is deliberate. A test fails when a component throws during rendering or in an event listener, rather than logging to the console and passing. If you provide your own ErrorHandler, yours is used. If you want to check that an error is reported, turn off rethrowing with rethrowApplicationErrors: false and use a spy handler.
import { ErrorHandler, Component, provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
@Component({
selector: 'app-save-button',
template: `<button (click)="save()">Save</button>`,
})
class SaveButton {
save(): void {
throw new Error('save failed');
}
}
describe('SaveButton', () => {
it('reports a click error to ErrorHandler', async () => {
const reported: unknown[] = [];
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
{ provide: ErrorHandler, useValue: { handleError: (e: unknown) => reported.push(e) } },
],
rethrowApplicationErrors: false,
});
const fixture = TestBed.createComponent(SaveButton);
await fixture.whenStable();
fixture.nativeElement.querySelector('button').click();
await fixture.whenStable();
expect(reported.length).toBe(1);
expect((reported[0] as Error).message).toBe('save failed');
});
});Leave rethrowApplicationErrors at its default for other tests. It helps you find errors you would otherwise miss.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Subscribing to `NgZone.onError` to log errors | Never fires in zoneless mode | Use a custom `ErrorHandler` |
| Omitting `provideBrowserGlobalErrorListeners()` | Timer and promise errors skip your logger | Add the provider |
| Throwing inside `handleError` | The original error is lost | Wrap reporting logic in `try`/`catch` |
| Updating a plain field in `handleError` to show a message | The view does not refresh | Write to a signal |
| Disabling test rethrow everywhere | Component errors pass unnoticed | Disable it only in tests that assert on errors |
Exercise
After switching an app to zoneless mode, your error logger no longer receives errors thrown inside setTimeout callbacks, though it still receives errors from (click) handlers. Why does this happen, and what is the fix?
Show answer
Click handlers declared in templates are called by Angular, which wraps them in its own try/catch and reports to ErrorHandler. A setTimeout callback was previously caught only because Zone.js patched setTimeout and NgZone.onError forwarded the error. Without the zone, the error becomes a plain browser error event that Angular ignores. Add provideBrowserGlobalErrorListeners() to the application providers so window error and unhandledrejection events are forwarded to ErrorHandler.
Exercise
A test uses a zoneless TestBed and clicks a button whose handler throws. You want the test to pass only if the error reaches ErrorHandler. What two changes make that possible?
Show answer
Provide a spy or fake ErrorHandler through the ErrorHandler token that records what it receives, and set rethrowApplicationErrors: false in configureTestingModule so the error is not rethrown and the test does not fail. Then click, await fixture.whenStable(), and assert on the recorded errors.