Sub topic 12
Reporting unhandled errors with ErrorHandler
This chapter assumes you can write a service that uses HttpClient, and that you know catchError and provideHttpClient. Earlier chapters handled errors where a request was made. Here you add a safety net for errors that nothing else handled.
What ErrorHandler does
ErrorHandler is an Angular class with one method, handleError(error). Angular calls it when an error escapes your code. Examples are an exception in a template expression, an exception inside an event handler, or an Observable error that no subscriber handled.
The default implementation writes the error to the browser console. You can replace it with your own class to log the error, send it to a monitoring service, or show a generic notice.
ErrorHandler does not replace catchError. It only sees errors that were not handled, so a request error that you caught and converted never reaches it.
Writing a custom handler
The handler below is the minimal version.
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
console.error('Unhandled error:', error);
}
}The parameter type is unknown because code can throw any value, not only Error objects. Check the type before you read properties from it.
Telling HTTP errors apart
An HttpErrorResponse can reach the handler when a subscriber has no error callback. Branch on the type so each kind of error is logged with useful detail.
import { HttpErrorResponse } from '@angular/common/http';
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
if (error instanceof HttpErrorResponse) {
if (error.status === 0) {
console.error('Unhandled network error:', error.message);
} else {
console.error(`Unhandled HTTP ${error.status} from ${error.url}`);
}
return;
}
if (error instanceof Error) {
console.error('Unhandled application error:', error.message, error.stack);
return;
}
console.error('Unhandled non-error value:', error);
}
}In a real application, replace console.error with a call to your logging service. Keep the handler short and make sure it never throws. An exception inside handleError has no further safety net.
Registering the handler
Register the class once in your application providers. Angular then uses it instead of the default.
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 },
],
};Common mistakes
- Expecting it to catch handled errors. If
catchErrorreturns a replacement value or a new error that your subscriber handles,ErrorHandleris never called. - Using it as the main error path. It has no context about which request failed or what the user was doing. Handle expected failures near the request and keep
ErrorHandlerfor surprises. - Logging sensitive data. Error objects can carry URLs, request bodies, or tokens. Remove them before you send errors to an external service.
- Reporting retried failures twice. If the retry interceptor gives up and the error is then unhandled, you get one report. Do not also log inside the interceptor.
Exercise
A service method uses catchError to rethrow new Error('Server returned 500'). A component subscribes with .subscribe(user => ...) and no error callback. Does the error reach your custom ErrorHandler? Why?
Show answer
Yes. catchError only changes the error, because the rethrown Error still travels down the stream. The subscriber has no error callback, so nothing handles it. The error escapes and Angular passes it to ErrorHandler.handleError. To keep it away from the global handler, add an error callback to subscribe.