错误处理
catchError
import { catchError, of, throwError } from "rxjs"
const loadConfig = () => throwError(() => new Error('配置加载失败'));
loadConfig().pipe(
catchError(err => {
console.error('Error loading config:', err.message);
// 提供一个默认配置作为替代
return of({ host: 'localhost', port: 8080 })
})
).subscribe(config => console.log(`Config: ${JSON.stringify(config)}`));import { catchError, of, throwError } from "rxjs"
const getAvatar$ = (userId) => {
return applyMixins.fetchUser(userId).pipe(
catchError(err => {
console.error('Error fetching avatar:', err.message);
// 返回一个默认头像 URL
return of('https://example.com/default-avatar.png')
})
)
}retry
import { defer, retry, tap, throwError } from "rxjs"
let attempts = 0;
const dbQuery$ = defer(() => {
attempts++;
return attempts < 3 ? throwError(() => 'Conn Refused') : of('Success!');
})
dbQuery$.pipe(
tap(val => console.log(`Attempt ${attempts}: ${val}`)),
retry(2) // 最多重试 2 次,加上初始尝试共 3 次
).subscribe({
next: res => console.log(`Query Result: ${res}`),
error: err => console.error(`Final Error after retries: ${err}`)
})import { retry } from "rxjs"
import { ajax } from "rxjs/ajax"
ajax("/api/data").pipe(
retry(3) // 失败时重试最多 3 次
).subscribe({
next: res => console.log(`Data: ${JSON.stringify(res.response)}`),
error: err => console.error(`Error fetching data: ${err}`)
})retryWhen
throwError
onErrorResumeNext
最后更新于