📖 Scenario: You are building a simple Angular service that fetches user data from an API. Sometimes the API might fail, so you want to handle errors gracefully.
🎯 Goal: Create an Angular service method that fetches user data and uses catchError to handle any errors by returning a friendly error message observable.
📋 What You'll Learn
Create a service method called getUserData that returns an observable
Use Angular's HttpClient to make a GET request to 'https://api.example.com/users'
Add a variable called errorMessage with the value 'Failed to load user data'
Use catchError from rxjs/operators to catch errors and return an observable of errorMessage
Ensure the service method returns the observable with error handling applied
💡 Why This Matters
🌍 Real World
Handling errors in HTTP requests is essential in real-world Angular apps to provide good user experience and avoid app crashes.
💼 Career
Knowing how to use catchError for error handling is a common requirement for Angular developers working with APIs.
Progress0 / 4 steps
1
Set up the Angular service and import HttpClient
Create an Angular service class called UserService and import HttpClient from @angular/common/http. Inject HttpClient in the constructor as private http: HttpClient.
Angular
Hint
Remember to import HttpClient and inject it in the constructor for making HTTP requests.
2
Add an error message variable
Inside the UserService class, add a variable called errorMessage and set it to the string 'Failed to load user data'.
Angular
Hint
Declare errorMessage as a class property with the exact string value.
3
Create getUserData method with HTTP GET request
Add a method called getUserData that returns the result of this.http.get('https://api.example.com/users').
Angular
Hint
Define getUserData to return the HTTP GET observable from the URL.
4
Use catchError to handle errors in getUserData
Import catchError from rxjs/operators and of from rxjs. Update getUserData to pipe the HTTP GET observable through catchError. Inside catchError, return of(this.errorMessage) to emit the error message observable.
Angular
Hint
Use pipe on the HTTP observable and inside it use catchError to return of(this.errorMessage).
Practice
(1/5)
1. What is the main purpose of catchError in Angular's RxJS?
easy
A. To delay the emission of values in an Observable
B. To catch errors in an Observable stream and handle them gracefully
C. To create a new Observable from scratch
D. To unsubscribe from an Observable automatically
Solution
Step 1: Understand what catchError does
catchError is used to catch errors that happen in an Observable stream and lets you handle them without breaking the stream.
Step 2: Compare with other options
Creating new Observables, delaying emissions, or unsubscribing are different RxJS tasks not related to catchError.
Final Answer:
To catch errors in an Observable stream and handle them gracefully -> Option B
Quick Check:
catchError handles errors [OK]
Hint: catchError is for handling errors inside Observable streams [OK]
Common Mistakes:
Thinking catchError creates Observables
Confusing catchError with delay or unsubscribe
Assuming catchError stops the Observable completely
2. Which of the following is the correct syntax to use catchError inside an Observable pipe?
easy
A. catchError(observable, error => of('Error caught'))
B. observable.catchError(error => of('Error caught'))
C. observable.pipe(catchError(error => of('Error caught')))
D. observable.pipe(catchError => error => of('Error caught'))
Solution
Step 1: Recall the correct usage of catchError
catchError is used inside pipe() and takes a function with an error parameter returning a new Observable.
Step 2: Identify the correct syntax
observable.pipe(catchError(error => of('Error caught'))) correctly uses pipe(catchError(error => of('Error caught'))). Other options misuse method chaining or syntax.
Final Answer:
observable.pipe(catchError(error => of('Error caught'))) -> Option C
Quick Check:
Use catchError inside pipe() [OK]
Hint: Always use catchError inside pipe() with a function [OK]
Common Mistakes:
Calling catchError directly on observable
Wrong arrow function syntax inside catchError
Passing catchError arguments incorrectly
3. Given the code below, what will be the output?
import { of, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
const source$ = throwError(() => new Error('Oops!'));
source$.pipe(
catchError(err => of('Error handled'))
).subscribe(value => console.log(value));
medium
A. Throws an error and stops
B. No output
C. Logs 'Oops!'
D. Logs 'Error handled'
Solution
Step 1: Understand throwError and catchError interaction
throwError creates an Observable that immediately errors. catchError catches this error and returns a new Observable emitting 'Error handled'.
Step 2: Trace the subscription output
The subscriber receives 'Error handled' and logs it. The original error is replaced by the catchError Observable.
Final Answer:
Logs 'Error handled' -> Option D
Quick Check:
catchError replaces error with new value [OK]
Hint: catchError replaces error with new Observable output [OK]
Common Mistakes:
Expecting original error to be logged
Thinking error stops the stream without catchError
Confusing error message with emitted value
4. Identify the error in this code snippet using catchError:
import { of, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
const source$ = throwError(() => new Error('Fail'));
source$.pipe(
catchError(err) {
return of('Recovered');
}
).subscribe(console.log);
medium
A. Missing parentheses around catchError argument function
B. Using throwError incorrectly
C. Not subscribing to the Observable
D. Returning a string instead of an Observable inside catchError
Solution
Step 1: Check catchError function syntax
The argument to catchError must be a function expression or arrow function inside parentheses. Here, parentheses are missing around the function.
Step 2: Verify other parts
throwError usage is correct, subscription exists, and return value inside catchError is an Observable (of('Recovered')), so no issues there.
Final Answer:
Missing parentheses around catchError argument function -> Option A
Quick Check:
Function argument to catchError needs parentheses [OK]
Hint: Wrap catchError callback in parentheses or use arrow function [OK]
Common Mistakes:
Omitting parentheses around function in catchError
Returning non-Observable values inside catchError
Not subscribing to see output
5. You want to retry an HTTP request up to 3 times and then handle errors gracefully using catchError. Which code snippet correctly combines retry and catchError?
hard
A. http.get(url).pipe(retry(3), catchError(err => of('Failed after retries')))
B. http.get(url).pipe(catchError(err => of('Failed')), retry(3))
C. http.get(url).pipe(catchError(err => retry(3)), of('Failed'))
D. http.get(url).pipe(retry(3).catchError(err => of('Failed')))
Solution
Step 1: Understand operator order in pipe
retry(3) should come before catchError so retries happen before error handling.
Step 2: Analyze each option
http.get(url).pipe(retry(3), catchError(err => of('Failed after retries'))) correctly chains retry(3) then catchError. http.get(url).pipe(catchError(err => of('Failed')), retry(3)) reverses order, so catchError stops retries. http.get(url).pipe(catchError(err => retry(3)), of('Failed')) misuses catchError and retry. http.get(url).pipe(retry(3).catchError(err => of('Failed'))) uses invalid chaining syntax.
Final Answer:
http.get(url).pipe(retry(3), catchError(err => of('Failed after retries'))) -> Option A
Quick Check:
retry before catchError in pipe [OK]
Hint: Place retry before catchError inside pipe() [OK]
Common Mistakes:
Putting catchError before retry disables retries
Using invalid chaining syntax
Returning non-Observable inside catchError
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.