To handle errors in Observables, use the following techniques:
1. catchError Operator
Catches errors and allows you to provide a fallback value or rethrow the error.
Example:
observable$.pipe(
catchError((error) => {
console.error('Error:', error);
return of('Fallback Value'); // Emit a fallback value
})
).subscribe((value) => console.log(value));
2. retry Operator
Retries the Observable a specified number of times on error.
Example:
observable$.pipe(
retry(3) // Retry up to 3 times
).subscribe((value) => console.log(value));
3. retryWhen Operator
Retries the Observable based on custom logic (e.g., after a delay).
Example:
observable$.pipe(
retryWhen((errors) => errors.pipe(delay(1000))) // Retry after 1 second
).subscribe((value) => console.log(value));
4. Error Callback in subscribe
Handle errors in the subscribe method.