Performance: catchError for error handling
This affects how asynchronous errors are handled without blocking UI responsiveness or causing unnecessary re-renders.
this.dataService.getData().pipe(catchError(err => { this.error = err; return of([]); })).subscribe(data => this.data = data);
this.dataService.getData().subscribe({ next: data => this.data = data, error: err => { this.error = err; throw err; } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Throw error inside subscribe | Multiple due to error propagation | Multiple reflows due to repeated change detection | High paint cost on error UI updates | [X] Bad |
| Use catchError with fallback | Minimal, only necessary updates | Single reflow for fallback UI | Low paint cost | [OK] Good |
catchError in Angular's RxJS?catchError is used to catch errors that happen in an Observable stream and lets you handle them without breaking the stream.catchError.catchError inside an Observable pipe?catchError is used inside pipe() and takes a function with an error parameter returning a new Observable.pipe(catchError(error => of('Error caught'))). Other options misuse method chaining or syntax.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));throwError creates an Observable that immediately errors. catchError catches this error and returns a new Observable emitting 'Error handled'.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);catchError must be a function expression or arrow function inside parentheses. Here, parentheses are missing around the function.of('Recovered')), so no issues there.catchError. Which code snippet correctly combines retry and catchError?retry(3) should come before catchError so retries happen before error handling.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.Pass the test and this pattern moves unknown