1

I have an interceptor to handle errors in my Angular app.
Also I have an input that has a keyup function that makes API calls.

My problem is that when the error is throw to the component the stream is stopped (normal behaviour because of onError in subscribe), so the keyup function doesn't work anymore.

My question is how can I manage this, so it doesn't end the stream when an error is thrown to the component ?

INTERCEPTOR :

export class HttpErrorInterceptor implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        let errorMsg = ''
        if (error.error instanceof ErrorEvent) {
          console.log('this is client side error')
          errorMsg = `Error: ${error.error.message}`
        }
        else {
          console.log('this is server side error')
          errorMsg = `Error Code: ${error.status},  Message: ${error.message}`
        }
        console.log(errorMsg)
        return throwError(errorMsg)
      }),
    )
  }
}

SERVICE :

search_address(query: string): Observable<Feature[]> {
  const url = 'https://api.mapbox.com/geocoding/v5/mapbox.places2/'
  return this.http.get<MapboxOutput>(url + query + '.json?limit=5&types=address&access_token=' + environment.mapboxToken).pipe(map((res: MapboxOutput) => {
    return res.features
  }))
}

COMPONENT :

ngOnInit() {
  // when keyup in input, trigger mapbox service to get addresses
  this.inputChanged.pipe(debounceTime(500), distinctUntilChanged(), mergeMap((searchTerm) => this.mapboxService.search_address(searchTerm)))
  .subscribe((features: Feature[]) => {
    this.addresses = features
  }, err => {
    console.log(err)
  })
}
PepeW
  • 477
  • 1
  • 8
  • 24

1 Answers1

0

I believe you want to use switchMap and handle the error in the inner observable so your observable chain won't die.

A more complete answer is here: How to keep observable alive after error in RxJS 6 and Angular 6

Wild Bill
  • 51
  • 1
  • 3
  • I have already seen this one but I don't what to return to the component because the Interceptor needs to return Observable> – PepeW Jun 20 '21 at 23:25
  • You can have multiple return value Observable> | Observable and return of(myError) in the error condition and catchError on search_address not subscribe as if you get to err on subscribe you are done. – Wild Bill Jun 20 '21 at 23:39
  • Can you edit your response and show how it can be done ? Even though I understand the theory, I can't make it work. Thank you – PepeW Jun 21 '21 at 10:17
  • because you can't return Observable> | Observable. The intercept method is "locked" because the class implements HttpInterceptor @Wild Bill – PepeW Jun 21 '21 at 20:06