Resilience in Communication: Mastering HTTP Error Handling in Angular
In a perfect world, every HTTP request receives a 200 OK response. But in reality, networks are flaky, servers crash, and users go offline. An unhandled error in Angular doesn't just fail silently; it can crash your application flow, leave loading spinners spinning forever, and frustrate your users.
The Anatomy of an HttpErrorResponse
When an HTTP request fails, Angular wraps the error in anHttpErrorResponse object. Understanding this object is the key to diagnosis.
Client-Side Errors
Status: 0.
These occur when the request never leaves the browser (e.g., network is offline) or an error occurs while executing the request.
Server-Side Errors
Status: 4xx or 5xx.
The server received the request but rejected it (404 Not Found, 403 Forbidden) or failed to process it (500 Internal Server Error).
Global vs. Local Error Handling
While using catchError in individual services gives you granular control, repeating that logic everywhere violates the DRY (Don't Repeat Yourself) principle. This is where HttpInterceptors shine.
An Interceptor sits between your application and the backend. It allows you to catch errors globally. For example, you can create an interceptor that listens specifically for 401 Unauthorized errors and automatically redirects the user to the login page, without every single service needing to know about authentication logic.
Pro Tip: Always distinguish between technical errors (for the console/logging) and user errors (for the UI). A user doesn't need to know about a "NullReferenceException," they just need to know "Service Unavailable."