0

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 Answers1

0
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);
  })
);
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Is there an explanation for why the error comes in the approach used in question? – emkay May 31 '19 at 05:20
  • This would not be the way I would do things but OP's api is returning a valid respose for an error hence why this hacky turd is needed. I would return an error from the api, not parse the response on the client to see if there was an error. – Adrian Brand May 31 '19 at 05:24
  • It doesn't seem like a hack. People do use it. See https://stackoverflow.com/questions/43199642/how-to-throw-error-from-rxjs-map-operator-angular I was curious why it din't work in op's case because it was working at my end. – emkay May 31 '19 at 05:30
  • 1
    https://stackblitz.com/edit/angular-reesff?file=src%2Fapp%2Fapp.component.ts throwing an error causes the whole component to stop working, that answer should not be marked as the accepted answer as it kills your app to throw a wild exception like that. – Adrian Brand May 31 '19 at 05:41