Angular 54: Error Handling
easy⏱ 5 mincourseangular
ErrorHandler is a single, overridable interception point
ErrorHandler is an injectable class with one method: handleError(error: unknown). Angular calls it for every error it catches internally, so implementing your own version — @Injectable() + implements ErrorHandler — gives you one place to log, report, or react to failures across the entire app.
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
console.error('[GlobalErrorHandler]', error);
}
}
Registering it replaces Angular's default handler app-wide
{ provide: ErrorHandler, useClass: GlobalErrorHandler } in the providers array tells Angular's injector: whenever anything asks for ErrorHandler, hand it a GlobalErrorHandler instance instead of the built-in default. Because ErrorHandler is used internally by Angular itself, this one provider swaps the behavior for the whole app.
export const appConfig: ApplicationConfig = {
providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }],
};
handleError takes unknown, not Error
Angular typed handleError to accept unknown because JavaScript lets you throw anything, not just Error instances. A production handler typically narrows it — checking error instanceof Error — before extracting a .message or .stack to report.