如何处理RXJ中的错误而不是尝试/捕获?
最初,错误处理如下。
async getLists() {
try {
const list = await api.getList();
list.filter() ....
} catch(e) {
console.log(e)
}
}
在同一情况下,如何使用RXJ处理它?
我不熟悉RXJ,所以我不知道这是否是答案,但是我想到的代码是这样。
getLists() {
from(api.getList()).subscribe(
list => list.filter.....,
e => console.log(e)
)
}
我想知道如何处理调用API时可能发生的所有错误,例如try-catch,以及处理API调用后从API接收到的数据时可能发生的错误。
API呼叫后正在返回承诺,但必须使用RXJ 如果发生错误,我想取消订阅。
Originally, the error is handled as follows.
async getLists() {
try {
const list = await api.getList();
list.filter() ....
} catch(e) {
console.log(e)
}
}
How can I handle it using rxjs in the same situation?
I'm not familiar with rxjs, so I don't know if it's the answer, but the code I thought of is like this.
getLists() {
from(api.getList()).subscribe(
list => list.filter.....,
e => console.log(e)
)
}
I want to know how to handle all the errors that may occur when calling the API, such as try-catch, and the errors that may occur when processing the data received from the API after the API call.
Promises are being returned after API calls, but rxjs must be used
If an error occurs, I want to unsubscribe.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
应该是一个体面的示例
这 是基于您的示例。您需要履行诺言,而不是可观察的。 (如@aakash Garg所述)。
So this should be a decent example of how to handle errors.
This is based on your example. You need to handle a promise, not an observable. (as mentioned by @Aakash Garg).
您可以使用订阅并处理这样的订阅错误:
让我知道它是否适合您。
You can use subscribe and handle subscribe error like this:
let me know if it works for you.
看来您的代码正在返回承诺,您可以将承诺转换为可观察的诺言,并订阅它,如下所示。
如果API调用成功,它将转到下一个块,如果发生任何错误,它将转到错误块。
注意: - 延期允许您仅在观察者订阅时创建可观察的。它等到观察者订阅它。
defer docs- https:/rxjs.dev/api/api/index/index/function/function/defer
It seems your code is returning a promise, you can convert the promise to observable and subscribe to it as shown below.
If the API call is successful it will go to the next block and if any error occurs it will go to the error block.
Note :- defer allows you to create an Observable only when the Observer subscribes. It waits until an Observer subscribes to it.
defer docs - https://rxjs.dev/api/index/function/defer