Skip to main content

Overview

HTTP requests can fail for many reasons: network errors, server errors, client errors, or timeouts. Angular provides robust error handling mechanisms through RxJS operators and the HttpErrorResponse class.

Error types

Angular distinguishes between two types of HTTP errors:

Client-side errors

Errors that occur in the browser:
  • Network connectivity issues
  • DNS resolution failures
  • Request cancellation
  • CORS errors

Server-side errors

Errors returned by the server:
  • 4xx client errors (400, 401, 403, 404, etc.)
  • 5xx server errors (500, 502, 503, etc.)
  • Invalid responses

HttpErrorResponse

The HttpErrorResponse object contains detailed error information:

Basic error handling

In subscriptions

Handle errors directly in the subscribe method:

Using catchError

Handle errors in the Observable pipe:

Centralized error handling

Error handler service

Create a service to centralize error handling logic:
error-handler.service.ts
Use the service in your HTTP calls:
user.service.ts

Error interceptor

Handle errors globally with an interceptor:
error.interceptor.ts
Register the interceptor:
app.config.ts

Retry logic

Simple retry

Retry failed requests automatically:

Conditional retry

Retry only for specific error types:

Advanced retry with retryWhen

Timeout handling

Set timeouts for requests:
Or use the timeout option in the request:

User feedback

Toast notifications

user.component.ts

Loading states

Show loading and error states:
user.component.ts

Specific error scenarios

Authentication errors

Network errors

Validation errors

Handle validation errors from the server:

Testing error handling

user.service.spec.ts

Best practices

Use centralized error handlingImplement a global error handler service or interceptor for consistent error handling across your application.
Provide meaningful feedbackShow user-friendly error messages instead of raw HTTP error messages.
Don’t swallow errors silently. Always log errors or notify users when something goes wrong.
Implement retry logic carefullyOnly retry idempotent operations (GET, PUT, DELETE) and avoid retrying POST requests that might create duplicate resources.
Handle different error typesDifferentiate between network errors (status 0), client errors (4xx), and server errors (5xx) for appropriate handling.
Use timeoutsAlways set reasonable timeouts to prevent requests from hanging indefinitely.

Next steps

HttpClient

Learn about making HTTP requests with HttpClient.

Interceptors

Transform requests and responses with interceptors.