简体   繁体   English

如何处理 rxjs 而不是 try/catch 中的错误?

[英]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.

相关问题 如何处理 try/catch 之外的错误? - How to handle errors outside try/catch? 尝试 - catch() 不捕捉错误而是抛出它 - Try - catch() not catching errors and throwing it instead Angular / rxJS:combineLatest - 如何处理 404 错误 - Angular / rxJS: combineLatest - how to handle 404 Errors 如何使用Angular处理RxJS中的错误 - How to handle errors in RxJS using Angular 如何通过使用try,throw,catch重新编写代码并最终处理错误? - how can I re-write the code by using try, throw, catch and finally to handle the errors? try-catch是否意味着防止或处理错误? (在javascript中) - Is try-catch meant to prevent or handle errors? (in javascript) 如何使用try catch捕获Javascript中的函数错误? - How to use try catch for function errors in Javascript? 如何在不尝试捕获的情况下全局捕获 JavaScript 错误 - How to catch JavaScript errors globally without try catch 如何使用低阶函数的 try catch 捕获错误 - How catch Errors with try catch of lower order functions 如何在没有try / catch的情况下捕获错误,或者在运行时使用try / catch打包代码? - How to catch errors without try/catch OR wrap code with try/catch in runtime?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM