puddlejumper26 / blogs

Personal Tech Blogs
4 stars 1 forks source link

Angular Rxjs catchError #128

Open puddlejumper26 opened 4 years ago

puddlejumper26 commented 4 years ago
catchError(project : function): Observable

Remember to return an observable from the catchError function!

catchError能捕获异常,且需要返回一个Observable,代码里的throw、throwError及其他JS错误均能被该操作符捕获。

需要注意的是,catchError捕获到异常后,数据源将不再执行。

代码示例

不添加catchError

from([1,2,3,4,5,6]).pipe(
  tap(v => {
    if (v == 3) throw 'err'
  })
).subscribe()

// console
1 2 error

添加catchError给from

from([1,2,3,4,5,6]).pipe(
  tap(v => {
    if (v == 3) throw 'err'
  }),
  catchError(err => of(err))
).subscribe()

// console
1 2 'err' complete

添加catchError给高阶函数

from([1,2,3,4,5,6]).pipe(
  mergeMap(v => {
    return of(v).pipe(
        tap(v => {
            if (v == 3) throw 'err'
        }),
        catchError(err => of(err))
    )
  })
).subscribe()

// console
1 2 'err' 4 5 6 complete

链接:https://www.jianshu.com/p/6db47d070030

Reference