[英]How to handle errors in rxjs instead of try/catch?
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?在相同情况下如何使用 rxjs 处理它?
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.我对rxjs不熟悉,所以不知道是不是答案,但是我想到的代码是这样的。
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.我想知道如何处理调用API时可能出现的所有错误,例如try-catch,以及API调用后处理从API收到的数据时可能出现的错误。
Promises are being returned after API calls, but rxjs must be used If an error occurs, I want to unsubscribe. API调用后正在返回Promises,但必须使用rxjs 如果出现错误,我想退订。
So this should be a decent example of how to handle errors.所以这应该是一个如何处理错误的好例子。
const getLists = getLists() {
from(api.getList()).pipe(catchError(error => of(`Bad Promise: ${error}`))
}
//output: 'Bad Promise: Rejected'
const subscribe = getLists.subscribe(val => console.log(val));
This is based on your example.这是基于你的例子。 You need to handle a promise, not an observable.
您需要处理 promise,而不是可观察对象。 (as mentioned by @Aakash Garg).
(正如@Aakash Garg 所提到的)。
You can use subscribe and handle subscribe error like this:您可以像这样使用订阅和处理订阅错误:
getLists() {
api.getList().subscribe(response => {
// do something with the response data
},
() => {
console.log('Error text');
})
}
let me know if it works for you.请让我知道这对你有没有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.