Angular Error Handling
Learn Angular error handling with HttpClient catchError, HTTP interceptors, the global ErrorHandler, RxJS retry strategies, user-friendly messages, best practices, and interview questions.
Every real application fails somewhere: the network drops, an API returns 500, or a template reads a property that does not exist. Error handling in Angular is about catching those failures in the right layer, reporting them, and keeping the user experience under control.
Table of Contents
- Types of Errors in Angular
- Handling HTTP Errors with catchError
- Centralised Handling with HTTP Interceptors
- Global ErrorHandler
- Retrying Failed Requests
- Best Practices
- Interview Questions
- Summary
Types of Errors in Angular
| Error Type | Example | Where to Handle |
|---|---|---|
| HTTP / network error | 404, 500, timeout, offline |
catchError in a service or an interceptor |
| Runtime error | TypeError, undefined property |
Global ErrorHandler |
| Validation error | Invalid form input | Reactive form validators and template messages |
| Business error | "Insufficient balance" from the API | Component or service, shown to the user |
Handling HTTP Errors with catchError
Handle errors close to the HttpClient call and map them into something the UI can use.
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, catchError, throwError } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) {}
getUser(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(
catchError((error: HttpErrorResponse) => {
const message =
error.status === 0
? 'Network error. Please check your connection.'
: error.error?.message ?? 'Something went wrong.';
return throwError(() => new Error(message));
})
);
}
}
error.status === 0 normally means the request never reached the server, for example when the user is offline or a CORS failure occurs.
Centralised Handling with HTTP Interceptors
An interceptor lets you handle common failures in one place instead of repeating catchError in every service.
import { HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
export const errorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((error) => {
if (error.status === 401) {
router.navigate(['/login']);
}
return throwError(() => error);
})
);
};
Register it with provideHttpClient(withInterceptors([errorInterceptor])).
Global ErrorHandler
Angular routes uncaught errors to the ErrorHandler class. Replace it to log errors to a monitoring service.
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
// send to a logging service such as Sentry or an internal API
console.error('Unhandled error:', error);
}
}
Provide it with { provide: ErrorHandler, useClass: GlobalErrorHandler }.
Retrying Failed Requests
Use retry for transient failures, and avoid retrying non-idempotent requests such as POST payments.
import { retry, timer } from 'rxjs';
this.http.get('/api/orders').pipe(
retry({ count: 3, delay: (_error, attempt) => timer(attempt * 1000) })
);
Best Practices
- Handle expected errors (validation, business rules) in the component or service, and unexpected ones globally.
- Never show raw server errors or stack traces to users.
- Log the error with context such as the URL, user ID and correlation ID.
- Retry only idempotent requests, with a limit and a backoff delay.
- Unsubscribe from long-lived streams, or use the
asyncpipe, so errors do not leak.
Interview Questions
1. How do you handle HTTP errors in Angular?
Use the catchError operator on the HttpClient observable to map the HttpErrorResponse into a user-friendly error. For cross-cutting concerns such as 401 handling, use an HTTP interceptor.
2. What is the Angular ErrorHandler?
It is the built-in service that receives uncaught errors. You can provide a custom implementation to send errors to a logging or monitoring service.
3. What is the difference between catchError and retry?
retry resubscribes to the source observable when it fails. catchError intercepts the error and lets you recover with a fallback value or rethrow a new error. They are often combined: retry first, then catchError.
4. Where should you handle errors, service or component?
Services should translate technical errors into meaningful ones. Components decide how to present them. Global concerns belong in interceptors or the global ErrorHandler.
Summary
- Use
catchErrorfor request-level errors and interceptors for shared behaviour. - Use a custom
ErrorHandlerfor uncaught runtime errors. - Retry carefully, and always show users a clear, safe message.
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.