前言

前几篇介绍过了

Creation Operators

Filter Operators

Join Creation Operators

这篇继续介绍 Error Handling Operators.

参考

RxJS 錯誤處理 Operators (1) - catchError / finalize / retry / retryWhen

Docs – Error Handling Operators

Observable and Subscriber Handler Error

Observable 的流程是 : Observable init > pipe > subscribe

不经过 pipe 的情况下, 处理 error 的方式如下:

const obs = new Observable(subscriber => {
subscriber.error('error message');
// throw 'error message'; // throw 也是可以
});
obs.subscribe({
error: errorMessage => console.log(errorMessage), // error message
});

简单明了.

catchError

catchError 是 pipe 阶段的 error handle. 它是 operator 来的.

catch error and change to succeeded

const obs = new Observable(subscriber => {
subscriber.error('error message');
});
obs
.pipe(
catchError(error => {
console.log(error); // error message
return of('succeeded');
})
)
.subscribe({
next: value => console.log(value), // succeeded
error: errorMessage => console.log(errorMessage), // won't call
});

catchError 接收到 error 后, 可以有几个处理方式. 上面这个是返回一个 "成功" 的 Observable, 这样 error 就不会在传下去了.

catch error and re-throw

catch error 然后继续往下 throw error,

throwError 方法之前介绍过了, 它是 Creation Operators 的一员.

catchError(error => {
return throwError(() => 're-throw error');
// throw 're-throw error'; // 用 throw 也可以
})

小结

总之, catchError 要返回一个 Observable, 可以是 succeeded 或者是 error

catchError(error => {
if (Math.random() < 0.5) {
return throwError(() => 're-throw error');
// throw 're-throw error'; // 用 throw 也可以
} else {
return of('succeeded');
}
})

catch error and retry

除了 succeeded 和 error, 还有一种处理方式是 retry. 所谓 retry 就是 unsubscribe 当前的 stream, 重新 subscribe Observable 得到新的 stream (旧的 Observable 会 displose, 新的会 init)

catchError((error, caught) => {
return caught;
})

返回 catchError 的第二个参数 caught 就表示要 retry. retry 可能会导致死循环的哦.

所以必须要有条件, 避开死循环, 比如:

catchError((error, caught) => {
if (Math.random() < 0.5) {
return caught; // retry
} else {
return of('succeeded');
}
})

delay retry

catchError((error, caught) => {
return timer(2000).pipe(switchMap(() => caught));
})

返回一个 delay 的 Observable 就可以延后 retry 了. 这里用了 switchMap 把 timer 的值换成了 caught observable. (这个 operator 我还没有介绍过的)

retry count

要计算 count 只能开一个外部的 variable 做记入. 或者封装一个自定义 operator. 但更简单的方法是直接用 RxJS 提供的 retry 和 retryWhen operator. 下面会介绍.

retry

用 catchError + caught 实现 retry 太费劲了, 所以 RxJS 封装了 retry operator

retry({
count: 3,
delay: 2000,
resetOnSuccess: false,
})

count 声明可以 retry 多少次

delay 声明 retry 的间隔时间, 有时候 error 是因为 server 繁忙, 只要等 1,2 秒在 retry 发 ajax 就可以解决了.

此外 delay 还支持更复杂的 config. 通过判断 error 和 retryCount 来决定要 delay 多少秒.

我们甚至可以返回 click$ 让 user 点击触发 retry.

也可以直接返回 throwError 结束 retry (即便还没有 hit 到 max retry count), 灵活就对了

delay: (error, retryCount) => timer(2000 * retryCount)

resetOnSuccess 声明当 retry 成功以后是否要 reset retry count. 默认值是 false, 通常 reset 是正确的, 所以一般我都是 set 成 true.

retryWhen

已经废弃了, 改用 retry + delay option 实现吧.

一句话总结

catchError : 在 pipe 中 catch error, 3中处理, 成功, 继续 error, retry

retry : 用 catchError 做 retry 太费劲就有了 retry operator

retryWhen : 废弃了, 改用 retry + delay option 实现.

RxJS 系列 – Error Handling Operators的更多相关文章

  1. [RxJS] Error handling operator: catch

    Most of the common RxJS operators are about transformation, combination or filtering, but this lesso ...

  2. Erlang error handling

    Erlang error handling Contents Preface try-catch Process link Erlang-way error handling OTP supervis ...

  3. MySQL Error Handling in Stored Procedures 2

    Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered ...

  4. setjmp()、longjmp() Linux Exception Handling/Error Handling、no-local goto

    目录 . 应用场景 . Use Case Code Analysis . 和setjmp.longjmp有关的glibc and eglibc 2.5, 2.7, 2.13 - Buffer Over ...

  5. Error Handling

    Use Exceptions Rather Than Return Codes Back in the distant past there were many languages that didn ...

  6. Error Handling and Exception

    The default error handling in PHP is very simple.An error message with filename, line number and a m ...

  7. Clean Code–Chapter 7 Error Handling

    Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...

  8. MySQL Error Handling in Stored Procedures---转载

    This tutorial shows you how to use MySQL handler to handle exceptions or errors encountered in store ...

  9. RxSwift 系列(三) -- Combination Operators

    RxSwift 系列(三) -- Combination Operators 前言 本篇文章将要学习如何将多个Observables组合成一个Observable. Combination Opera ...

  10. Error Handling in ASP.NET Core

    Error Handling in ASP.NET Core 前言  在程序中,经常需要处理比如 404,500 ,502等错误,如果直接返回错误的调用堆栈的具体信息,显然大部分的用户看到是一脸懵逼的 ...

随机推荐

  1. 10.2 web服务器

    Web客户端和服务器之间的交互用的是一个基于文本的应用级协议,叫做HTTP(Hypertext Transfer Protocol,超文本传输协议).HTTP是一个简单的协议.一个Web客户端(即浏览 ...

  2. tp5生命周期

    https://www.kancloud.cn/manual/thinkphp5/118011 1.入口文件 用户发起的请求都会经过应用的入口文件,通常是 public/index.php文件.当然, ...

  3. webpack4.15.1 学习笔记(二) — 配置及开发环境构建

    目录 基本安装 配置文件 管理资源 管理输出 构建一个开发环境 使用 source map 选择一个开发工具 观察模式 webpack-dev-server webpack-dev-middlewar ...

  4. microsoft office object版本对应offices版本

    1997年 Excel 97 Microsoft Excel 8.0 1999年 Excel 2000 Microsoft Excel 9.0 2001年 Excel XP Microsoft Exc ...

  5. java+mysql+tomcat环境变量配置(windows版)

    jdk8(本人用的jdk8) 系统变量->新建:{JAVA_HOME=[JDK安装目录]} 系统变量->PATH:头部追加%JAVA_HOME%\bin;%JAVA_HOME%\jre\b ...

  6. HCIA first

    每台电脑都有网线 网线连的是什么? 网线插在接入交换机 流量给入汇聚交换机 汇聚给核心交换机 核心交换机 堆叠是指将一台以上的交换机组合起来共同工作,以便在有限的空间内提供尽可能多的端口.多台交换机经 ...

  7. Jmeter函数助手16-StringFromFile

    StringFromFile函数用于获取文本文件的值,一次读取一行,可读取多个文件. 输入文件的全路径:填入文件路径 存储结果的变量名(可选) Start file sequence number ( ...

  8. 【Scala】03 函数

    1.Scala的方法语法: object Hello { def main(args : Array[String]) : Unit = { // scala 允许在方法的声明中再声明方法,并且调用 ...

  9. 【IDEA】DEBUG调试问题

    不要将断点打在方法的声明上: 会有一个菱形标志,在标记之后运行DEBUG模式会跑不起来 查看所有的断点标记: 在这里直接找到所有标记位置,弄掉就会跑起来了

  10. 【FastDFS】环境搭建 02 测试

    自带工具测试: 编辑客户端配置文件: vim client.conf 配置完成后,随便上传一个图片到root目录下 运行FastFDS文件上传程序,并将客户端配置文件作为加载参数1,要上传的图片文件位 ...