- 默认的error
of(1, 2, 3, 4, 5).pipe(
map(
n => {
if (n === 4) {
throw new Error('four err')
}
return n;
}
)
).subscribe(
x => console.log(x),
error => console.error('err', error),
() => console.log('complete')
)
//1
//2
//3
//four err
catchError
无视错误,返回新的Observable
of(1, 2, 3, 4, 5).pipe(
map(
n => {
if (n === 4) {
throw new Error('four err')
}
return n;
}
),
catchError(err => of('捕获错误')),
).subscribe(
x => console.log(x),
error => console.error('err', error),
() => console.log('complete')
)
//1
//2
//3
//捕获错误
//complete
- 重试错误
捕获到错误时,重试时要加take,否则会报错
Maximum call stack size exceeded
of(1, 2, 3, 4, 5).pipe(
map(
n => {
if (n === 4) {
throw new Error('four err')
}
return n;
}
),
catchError((err, caught) => caught),
take(30)
).subscribe(
x => console.log(x),
error => console.error('err', error),
() => console.log('complete')
)
retry
发生错误后重试指定次数
of(1, 2, 3, 4, 5).pipe(
map(
n => {
if (n === 4) {
throw new Error('four err')
}
return n;
}
),
retry(2)
).subscribe(
x => console.log(x),
error => console.error('err', error),
() => console.log('complete')
)
retryWhen
发生错误后,自定义重试策略,参数是个回调函数,返回Observalbe
const source = interval(1000)
const example = source.pipe(
map(val => {
if (val > 5) {
//错误由retryWhen接收
throw val;
}
return val;
}),
retryWhen(errors =>
errors.pipe(
tap(val => console.log(`${val}太大了`)),
delay(3000)
)
)
)
const subscribe = example.subscribe(
val => console.log(val),
error => console.error('err ', error)
)
// 1 2 3 4 5 6太大了(延迟3秒后重试)
网友评论