Bird
Raised Fist0
Angularframework~20 mins

Handling HTTP errors in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
HTTP Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when the HTTP request fails in this Angular service?
Consider this Angular service method that fetches user data. What will the component receive if the HTTP request returns a 404 error?
Angular
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private http: HttpClient) {}

  getUser(id: number) {
    return this.http.get(`/api/users/${id}`).pipe(
      catchError(error => {
        return throwError(() => new Error('User not found'));
      })
    );
  }
}
AThe component receives null.
BThe component receives the original HTTP error object.
CThe component receives an error with message 'User not found'.
DThe component receives an empty object {}.
Attempts:
2 left
💡 Hint
Look at what the catchError operator returns inside the pipe.
📝 Syntax
intermediate
2:00remaining
Which option correctly handles HTTP errors using Angular's HttpClient?
Choose the code snippet that correctly catches HTTP errors and returns a fallback value.
Angular
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, of } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(private http: HttpClient) {}

  fetchData() {
    return this.http.get('/api/data').pipe(
      // error handling here
    );
  }
}
AcatchError(error => of({ data: [] }))
BcatchError(error => { return { data: [] }; })
CcatchError(error => throwError(() => new Error('Error occurred')))
DcatchError(error => console.log(error))
Attempts:
2 left
💡 Hint
Remember catchError expects an observable to be returned.
🔧 Debug
advanced
2:30remaining
Why does this Angular HTTP error handler not catch errors?
This Angular service method tries to catch HTTP errors but errors still propagate unhandled. What is the problem?
Angular
getData() {
  this.http.get('/api/data').subscribe({
    next: data => console.log(data),
    error: err => console.error('Error:', err)
  });

  return this.http.get('/api/data').pipe(
    catchError(err => {
      console.log('Caught error');
      return of([]);
    })
  );
}
AThe first HTTP call subscribes without catchError, so errors are not caught there.
BThe catchError operator is used incorrectly inside subscribe.
CThe catchError operator must be placed after subscribe.
DThe service returns two observables causing conflict.
Attempts:
2 left
💡 Hint
Check where the subscription happens and if catchError is applied before it.
❓ state_output
advanced
2:00remaining
What is the component's errorMessage after this HTTP error handling?
In this Angular component, what will be the value of errorMessage after a 500 server error occurs?
Angular
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Component({
  selector: 'app-data',
  template: `<p>{{ errorMessage }}</p>`
})
export class DataComponent {
  errorMessage = '';

  constructor(private http: HttpClient) {
    this.http.get('/api/data').pipe(
      catchError(err => {
        this.errorMessage = 'Server error occurred';
        return throwError(() => err);
      })
    ).subscribe({
      next: data => console.log(data),
      error: err => console.log('Error handled in subscribe')
    });
  }
}
A'' (empty string)
B'Server error occurred'
C'Error handled in subscribe'
Dundefined
Attempts:
2 left
💡 Hint
Look at when errorMessage is set inside catchError.
🧠 Conceptual
expert
2:30remaining
Which statement about Angular HTTP error handling is true?
Select the correct statement about handling HTTP errors in Angular using HttpClient and RxJS.
AAngular requires try-catch blocks around HTTP calls to catch errors.
BErrors must be handled only inside subscribe's error callback for proper catching.
CHttpClient automatically retries failed requests without extra code.
DUsing catchError inside pipe allows transforming or recovering from errors before subscription.
Attempts:
2 left
💡 Hint
Think about where RxJS operators like catchError work in the observable chain.

Practice

(1/5)
1. What is the main purpose of using catchError in Angular HTTP requests?
easy
A. To handle errors that occur during the HTTP request
B. To retry the HTTP request automatically
C. To transform the HTTP response data
D. To cancel the HTTP request

Solution

  1. Step 1: Understand the role of catchError

    catchError is used to catch errors in an observable stream, such as HTTP requests.
  2. Step 2: Identify its purpose in HTTP requests

    It allows handling errors gracefully instead of letting them crash the app or go unhandled.
  3. Final Answer:

    To handle errors that occur during the HTTP request -> Option A
  4. Quick 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
A. this.http.get(url).catchError(error => throwError(error))
B. this.http.get(url).pipe(catchError(error => throwError(() => error)))
C. this.http.get(url).pipe(map(error => throwError(error)))
D. this.http.get(url).subscribe(catchError(error => throwError(error)))

Solution

  1. Step 1: Recognize correct RxJS operator usage

    In Angular, pipe() is used to chain operators like catchError.
  2. Step 2: Check the syntax of catchError

    The correct form is catchError(error => throwError(() => error)) inside pipe().
  3. Final Answer:

    this.http.get(url).pipe(catchError(error => throwError(() => error))) -> Option B
  4. Quick 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:
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
A. The HTTP request is retried automatically
B. The error is ignored and the observable completes successfully
C. The error is logged and a new error is passed to subscribers
D. The app crashes due to unhandled error

Solution

  1. Step 1: Analyze catchError behavior on failure

    When the HTTP request fails, catchError runs, logging the error message.
  2. Step 2: Understand throwError usage

    It returns a new error observable with a friendly message, passing it to subscribers.
  3. Final Answer:

    The error is logged and a new error is passed to subscribers -> Option C
  4. Quick 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
A. throwError should be called with a function: throwError(() => error)
B. catchError should be outside pipe()
C. subscribe should be before pipe()
D. console.log cannot be used inside catchError

Solution

  1. Step 1: Check throwError usage

    In RxJS 7+, throwError requires a function returning the error: throwError(() => error).
  2. Step 2: Verify catchError and subscribe placement

    catchError must be inside pipe(), and subscribe after pipe(), which is correct here.
  3. Final Answer:

    throwError should be called with a function: throwError(() => error) -> Option A
  4. Quick 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
A. return this.http.get(url).pipe(catchError(err => { console.error(err); return of('Error occurred'); }))
B. return this.http.get(url).pipe(catchError(err => { return throwError(() => new Error('Error occurred')); }))
C. return this.http.get(url).pipe(catchError(err => { alert(err.message); return throwError(() => err); }))
D. return this.http.get(url).pipe(catchError(err => { alert('Error occurred'); console.error(err); return throwError(() => err); }))

Solution

  1. 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.
  2. Step 2: Verify error propagation

    It returns throwError(() => err) to pass the error downstream for further handling.
  3. Final Answer:

    return this.http.get(url).pipe(catchError(err => { alert('Error occurred'); console.error(err); return throwError(() => err); })) -> Option D
  4. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard