jufracaqui
jufracaqui

Reputation: 234

Angular 4 - Return HttpErrorResponse from interceptor

This in my interceptor

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .catch(err => {
        if (err instanceof HttpErrorResponse) {
          this.errorControl(req, err.status);
          return Observable.throw(err);
        }
      });
  }

I need to catch the error sent from the server in my component since I have to act accordingly (404: return to last url, 400: show a message, etc). When I catch the error in the subscription to the observable I get this

"You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable."

but I need a HttpErrorResponse with its status, status text, etc.

Removing the interceptor solves my problem, but I need it for all the session stuff.

Upvotes: 2

Views: 7188

Answers (1)

user4676340
user4676340

Reputation:

Your code is this :

if (err instanceof HttpErrorResponse) {
  this.errorControl(req, err.status);
  return Observable.throw(err);
}

But I don't see an else anywhere !

This means you aren't returning the error when your error isn't an instance of HttpErrorResponse.

You should return an Observable in any case, not only when it suits you.

Upvotes: 2

Related Questions