错误处理

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)}`));

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}`)
})

retryWhen

throwError

onErrorResumeNext

最后更新于