RxJS@6 fromFetch with catchError 无法捕获错误

问题描述 投票:0回答:1

我想在 vanilla JS 中使用 RxJS 的

fromFetch
方法来改进遗留代码中的纯
fetch
调用。

看起来像这样:

fromFetch(`${requestUrl}`, {
  method: 'GET',
  headers: {
    Authorization: `Bearer ${token}`
  },
  selector: (response) => response.json(),
}).pipe(
  catchError((err) => {
    // Do something with the error, then throw a custom error:
    return throwError('My Custom Error Message');
  }),
);

在我订阅的地方看起来像:

observable.subscribe({
  next: () => {},
  error: () => {
    // Handle errors
  },
});

完成所有这些错误处理后,有时(我不知道为什么),但屏幕上会出现错误消息:

我应该如何捕获 fetch 中的错误?也许错误来自

selector: (response) => response.json()
,我应该将其移出并处理那里的错误?

javascript rxjs fetch-api
1个回答
0
投票

您可以尝试在

throwError
中放入一个回调,这将返回一个错误类!

import './style.css';

import { catchError, throwError } from 'rxjs';
import { fromFetch } from 'rxjs/fetch';

// Open the console in the bottom right to see results.
fromFetch(`https://jsonplaceholder.typicoasdfasdfde.com/todos3/1`, {
  method: 'GET',
  selector: (response: any) => response.json(),
})
  .pipe(
    catchError((err) => {
      // Do something with the error, then throw a custom error:
      return throwError(() => new Error('My Custom Error Message'));
    })
  )
  .subscribe({
    next: (asdf: any) => console.log('next', asdf),
    error: (error: any) => console.log('error', error.message),
  });

Stackblitz 演示

© www.soinside.com 2019 - 2024. All rights reserved.