throwError
Last updated
import { throwError } from 'rxjs';
// Create an observable that immediately emits an error
const error$ = throwError(() => new Error('Something went wrong!'));
// Subscribe to see the error
error$.subscribe({
next: val => console.log('Next:', val), // Won't be called
error: err => console.error('Error caught:', err.message),
complete: () => console.log('Complete!') // Won't be called
});
// Output: "Error caught: Something went wrong!"import { of, throwError } from 'rxjs';
import { mergeMap, catchError } from 'rxjs/operators';
interface User {
id: number;
name: string;
}
// Simulate fetching user data
function fetchUser(id: number) {
return of({ id, name: `User ${id}` });
}
// Validate user ID before fetching - handle errors per item
of(0, 5, -1, 10)
.pipe(
mergeMap((id) => {
// Create the source observable based on validation
const source$ =
id <= 0
? throwError(() => new Error(`Invalid user ID: ${id}`))
: fetchUser(id);
// Handle errors for each item individually
return source$.pipe(
catchError((err) => {
console.error('Caught:', err());
// Provide fallback user for this item only
return of({ id: 0, name: 'Guest User' } as User);
})
);
})
)
.subscribe((user) => console.log('User:', user.name));
/* Output:
Caught: Invalid user ID: 0
User: Guest User
User: User 5
Caught: Invalid user ID: -1
User: Guest User
User: User 10
*/import { of, throwError, timer } from 'rxjs';
import { mergeMap, retry, tap } from 'rxjs/operators';
let attemptCount = 0;
// Simulate an unreliable API call
function unreliableApiCall() {
attemptCount++;
console.log(`API call attempt #${attemptCount}`);
// Fail first 2 attempts, succeed on 3rd
return attemptCount < 3
? throwError(() => new Error('Network timeout'))
: of({ data: 'Success!' });
}
// Try the API call with retry logic
of(null).pipe(
mergeMap(() => unreliableApiCall()),
retry(2) // Retry up to 2 times on error
).subscribe({
next: result => console.log('Result:', result.data),
error: err => console.error('Final error:', err.message)
});
/* Output:
API call attempt #1
API call attempt #2
API call attempt #3
Result: Success!
*/