Handling HTTP errors helps your app respond nicely when something goes wrong with data requests. It keeps users informed and prevents crashes.
Handling HTTP errors in Angular
Introduction
Syntax
Angular
import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; this.http.get('url').pipe( catchError(error => { // handle error here return throwError(() => new Error(error.message)); }) ).subscribe( data => { /* use data */ }, error => { /* handle error in subscription */ } );
Use catchError inside pipe() to catch errors from HTTP calls.
Return throwError to pass the error to the subscriber.
Examples
Angular
this.http.get('api/data').pipe( catchError(err => { console.error('Error occurred:', err.message); return throwError(() => new Error('Failed to load data')); }) ).subscribe( data => console.log(data), error => alert(error.message) );
Angular
this.http.post('api/save', payload).pipe( catchError(err => { if (err.status === 404) { return throwError(() => new Error('Resource not found')); } return throwError(() => new Error('Unknown error')); }) ).subscribe( response => console.log('Saved'), error => console.log(error.message) );
Sample Program
This Angular component tries to load data from a wrong URL to simulate an error. It shows a red error message when the HTTP call fails.
Angular
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { throwError } from 'rxjs'; @Component({ selector: 'app-error-demo', template: ` <button (click)="loadData()">Load Data</button> <p *ngIf="errorMessage" style="color: red;">{{ errorMessage }}</p> <pre *ngIf="data">{{ data | json }}</pre> ` }) export class ErrorDemoComponent { data: any = null; errorMessage = ''; constructor(private http: HttpClient) {} loadData() { this.errorMessage = ''; this.data = null; this.http.get('https://jsonplaceholder.typicode.com/invalid-url') .pipe( catchError(err => { this.errorMessage = 'Failed to load data: ' + err.message; return throwError(() => new Error(err.message)); }) ) .subscribe({ next: res => this.data = res, error: () => {} }); } }
Important Notes
Always handle errors to avoid app crashes and improve user experience.
You can customize error messages based on error status or content.
Use Angular's HttpClient and RxJS operators for clean error handling.
Summary
Use catchError inside pipe() to catch HTTP errors.
Return throwError to pass errors to subscribers.
Show friendly messages to users when errors happen.
Practice
1. What is the main purpose of using
catchError in Angular HTTP requests?easy
Solution
Step 1: Understand the role of
catchErrorcatchErroris used to catch errors in an observable stream, such as HTTP requests.Step 2: Identify its purpose in HTTP requests
It allows handling errors gracefully instead of letting them crash the app or go unhandled.Final Answer:
To handle errors that occur during the HTTP request -> Option AQuick Check:
catchError handles HTTP errors = A [OK]
Hint: Remember catchError catches errors in observable streams [OK]
Common Mistakes:
- Thinking catchError retries requests automatically
- Confusing catchError with data transformation operators
- Assuming catchError cancels requests
2. Which of the following is the correct syntax to catch HTTP errors in Angular using RxJS operators?
easy
Solution
Step 1: Recognize correct RxJS operator usage
In Angular,pipe()is used to chain operators likecatchError.Step 2: Check the syntax of catchError
The correct form iscatchError(error => throwError(() => error))insidepipe().Final Answer:
this.http.get(url).pipe(catchError(error => throwError(() => error))) -> Option BQuick Check:
Use pipe with catchError and throwError = B [OK]
Hint: Always use pipe() to chain catchError in Angular HTTP calls [OK]
Common Mistakes:
- Using catchError outside pipe()
- Using map instead of catchError for errors
- Passing throwError without a function wrapper
3. Consider this Angular service code snippet:
What will happen when the HTTP request fails?
getData() {
return this.http.get('/api/data').pipe(
catchError(err => {
console.error('Error:', err.message);
return throwError(() => new Error('Failed to load data'));
})
);
}What will happen when the HTTP request fails?
medium
Solution
Step 1: Analyze catchError behavior on failure
When the HTTP request fails, catchError runs, logging the error message.Step 2: Understand throwError usage
It returns a new error observable with a friendly message, passing it to subscribers.Final Answer:
The error is logged and a new error is passed to subscribers -> Option CQuick Check:
catchError logs and rethrows error = A [OK]
Hint: catchError logs error then returns throwError to notify subscribers [OK]
Common Mistakes:
- Assuming error is ignored or swallowed
- Thinking HTTP request retries automatically
- Believing app crashes without catchError
4. Identify the error in this Angular HTTP error handling code:
this.http.get('/api/items').pipe(
catchError(error => {
console.log('Error:', error);
return throwError(error);
})
).subscribe(data => console.log(data));medium
Solution
Step 1: Check throwError usage
In RxJS 7+, throwError requires a function returning the error:throwError(() => error).Step 2: Verify catchError and subscribe placement
catchError must be inside pipe(), and subscribe after pipe(), which is correct here.Final Answer:
throwError should be called with a function: throwError(() => error) -> Option AQuick Check:
throwError needs function wrapper = D [OK]
Hint: Use throwError(() => error) to avoid RxJS errors [OK]
Common Mistakes:
- Calling throwError directly with error object
- Placing catchError outside pipe()
- Misordering subscribe and pipe()
5. You want to show a friendly message to users when an HTTP error occurs, but still log the original error for debugging. Which code snippet correctly implements this in Angular?
hard
Solution
Step 1: Check user notification and logging
return this.http.get(url).pipe(catchError(err => { alert('Error occurred'); console.error(err); return throwError(() => err); })) shows an alert to users and logs the error to console, fulfilling both requirements.Step 2: Verify error propagation
It returnsthrowError(() => err)to pass the error downstream for further handling.Final Answer:
return this.http.get(url).pipe(catchError(err => { alert('Error occurred'); console.error(err); return throwError(() => err); })) -> Option DQuick Check:
Alert user + log error + rethrow = C [OK]
Hint: Alert user, log error, then rethrow with throwError(() => err) [OK]
Common Mistakes:
- Not alerting user or not logging error
- Returning a string instead of throwing error
- Alerting raw error message confusing users
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
