How would you handle errors from an HTTP request in Angular, showing a friendly message to the user?
Short answer
You use the catchError operator inside the observable's pipe, letting you catch any error the request throws, log it if needed, and return a fallback value or rethrow a more user friendly error that your component can display appropriately.
Advertisement
AModel answer
You use the catchError operator inside the observable's pipe, letting you catch any error the request throws, log it if needed, and return a fallback value or rethrow a more user friendly error that your component can display appropriately.
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
getUsers() {
return this.http.get<User[]>('/api/users').pipe(
catchError((error) => {
console.error('Failed to load users', error);
return of([]); // fallback to an empty list instead of crashing
})
);
}Real-world example
A user list page shows an empty state message instead of a broken page when the backend API is temporarily unavailable, thanks to catchError providing a safe fallback value for the component to display.
Likely follow-ups
- What is the difference between handling an error with catchError versus in the subscribe method's error callback?
- How would you show a specific error message based on the actual HTTP status code returned?
Related topics