【问题标题】:How to emulate error in map pipe RXJS (Angular)?如何在地图管道 RXJS(Angular)中模拟错误?
【发布时间】:2019-10-16 11:40:46
【问题描述】:

如果我得到代码“ERROR”,我会尝试在地图函数中返回错误。

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const request = req.clone();

    return next.handle(request).pipe(
      map((event: any) => {
        if (event instanceof HttpResponse) {
          if (event.body && event.body.code === 'ERROR') {
            throw new Error('Fatal Error');
          }
          const body = event.body ? event.body.body || event.body : null;

          if (body) {
            return event.clone({body});
          }
        }

        return event;
      })
    );
  }
}

但我在控制台中发现错误:

core.js:15724 错误类型错误:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。 在 subscribeTo (subscribeTo.js:41) 在 subscribeToResult (subscribeToResult.js:11)

【问题讨论】:

    标签: angular typescript rxjs angular-http-interceptors


    【解决方案1】:
    import { throwError } from 'rxjs';
    
    throwError('I made a boo boo')
    

    你不能在地图中使用它,所以你需要 switchMap

    return next.handle(request).pipe(
      switchMap((event: any) => {
        if (event instanceof HttpResponse) {
          if (event.body && event.body.code === 'ERROR') {
            return throwError('Fatal Error');
          }
          const body = event.body ? event.body.body || event.body : null;
    
          if (body) {
            return of(event.clone({body}));
          }
        }
    
        return of(event);
      })
    );
    

    【讨论】:

    • 有没有解释为什么错误出现在所讨论的方法中?
    • 这不是我做事的方式,但 OP 的 api 正在为错误返回一个有效的响应,因此为什么需要这个 hacky turd。我会从 api 返回一个错误,而不是在客户端解析响应以查看是否有错误。
    • 这看起来不像是 hack。人们确实使用它。请参阅stackoverflow.com/questions/43199642/… 我很好奇为什么它在 op 的情况下不起作用,因为它在我的末端起作用。
    • stackblitz.com/edit/… 抛出错误会导致整个组件停止工作,该答案不应被标记为已接受的答案,因为它会杀死您的应用程序以引发类似的异常。
    猜你喜欢
    • 2019-03-03
    • 2020-06-14
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2018-11-02
    • 1970-01-01
    相关资源
    最近更新 更多