Handling Responses and Errors
When making HTTP requests, things don't always go smoothly – networks fail, servers return errors. Properly handling responses and errors is crucial for a good user experience.
Typing Responses
You can specify the expected response type to get better type safety.
getPosts(): Observable {
return this.http.get('/api/posts');
}
Handling Success Responses
In your component, you handle the data as usual. But what about errors?
Handling Errors with catchError
Use RxJS
catchError operator to handle errors in your service.import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
getPosts(): Observable {
return this.http.get('/api/posts').pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// Client-side or network error
console.error('An error occurred:', error.error.message);
} else {
// Backend returned unsuccessful response code
console.error(`Backend returned code ${error.status}, body was:`, error.error);
}
// Return an observable with a user-facing error message
return throwError('Something bad happened; please try again later.');
}
Handling Errors in Component
In the component, you can handle the error in the subscribe call.
this.dataService.getPosts().subscribe({
next: (data) => this.posts = data,
error: (err) => this.errorMessage = err
});
Retry Failed Requests
Sometimes you want to retry failed requests. Use
retry operator.import { retry } from 'rxjs/operators';
getPosts(): Observable {
return this.http.get('/api/posts').pipe(
retry(3), // retry up to 3 times
catchError(this.handleError)
);
}
Two Minute Drill
- Type responses for better type safety.
- Use catchError to handle and transform errors.
- Distinguish client-side vs server-side errors.
- Handle errors in component subscription.
- Use retry operator to automatically retry failed requests.
Need more clarification?
Drop us an email at career@quipoinfotech.com
