Skip to content

Instantly share code, notes, and snippets.

@melcor76
Last active February 21, 2023 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melcor76/1e95ebfe2a9d0c39e60559258fd9b241 to your computer and use it in GitHub Desktop.
Save melcor76/1e95ebfe2a9d0c39e60559258fd9b241 to your computer and use it in GitHub Desktop.
Error handling - server-error.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpRequest, HttpHandler,
HttpInterceptor, HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable()
export class ServerErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
// refresh token
} else {
return throwError(error);
}
})
);
}
}
@Djordje-Susic
Copy link

This code gives me error "ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable". The problem is that interceptor must return Observable<HttpEvent> but line 20 ("return throwError(error);") is in else block so if line 17 condition is true it never returns it.

@DiegoVenancioVieira
Copy link

throwError(error); ==> Deprecated
instead, use it: return throwError(() => error);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment