0
votes

I try return error in map function, if i get code "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;
      })
    );
  }
}

But i catch error in console:

core.js:15724 ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable. at subscribeTo (subscribeTo.js:41) at subscribeToResult (subscribeToResult.js:11)

1

1 Answers

0
votes
import { throwError } from 'rxjs';

throwError('I made a boo boo')

You cannot use it in a map so you would need to 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);
  })
);