0
0
Angularframework~20 mins

Handling HTTP errors in Angular - Practice Problems & Coding Challenges

Choose your learning style9 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.