Performance: Handling HTTP errors
This affects the responsiveness and smoothness of user interactions by managing how HTTP errors impact UI updates and loading states.
this.http.get('/api/data').pipe(catchError(err => { this.errorMessage = 'Failed to load data'; return of([]); })).subscribe(data => { this.data = data; });
this.http.get('/api/data').subscribe(data => { this.data = data; }, error => { alert('Error occurred'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking alert on error | Minimal | 0 | Blocks UI thread causing delayed paint | [X] Bad |
| Non-blocking catchError with fallback | Minimal | 1 (UI update) | Efficient paint with minimal reflow | [OK] Good |
| Blind retry without delay | Minimal | 0 | Delays error feedback, increasing perceived latency | [!] OK |
| Retry with delay and limit | Minimal | 1 (UI update) | Balanced paint cost with timely feedback | [OK] Good |
catchError in Angular HTTP requests?catchErrorcatchError is used to catch errors in an observable stream, such as HTTP requests.pipe() is used to chain operators like catchError.catchError(error => throwError(() => error)) inside pipe().getData() {
return this.http.get('/api/data').pipe(
catchError(err => {
console.error('Error:', err.message);
return throwError(() => new Error('Failed to load data'));
})
);
}this.http.get('/api/items').pipe(
catchError(error => {
console.log('Error:', error);
return throwError(error);
})
).subscribe(data => console.log(data));throwError(() => error).throwError(() => err) to pass the error downstream for further handling.Pass the test and this pattern moves unknown