How do you perform error handling in Observable s?
How do you perform error handling in Observable s?
Error handling in Angular Observables is a crucial aspect of building robust applications. Angular leverages RxJS, a library for reactive programming, to handle asynchronous data streams through Observables. Proper error handling ensures that applications can gracefully manage and respond to errors that occur during these data flows. Here’s a comprehensive overview of how to perform error handling in Observables:
catchError
OperatorThe primary method for handling errors in Angular Observables is through the catchError
operator. This operator intercepts an error that occurs in an Observable stream and allows developers to handle it effectively. The catchError
function takes a function as an argument, which receives the error and returns a new Observable or throws an error.
Here’s a basic example of using catchError
:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
this.httpClient.get('/api/data').pipe(
catchError((error: any) => {
console.error('An error occurred:', error);
return throwError('Something went wrong');
})
).subscribe(
response => {
// Handle the successful response
},
error => {
// This block will only execute if catchError does not handle the error
console.error('Unhandled error:', error);
}
);
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào