0
votes

I am developing an interceptor for handling http error in angular 10 project. Here is the code:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class HttpErrorHandlerServiceService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
    .pipe(
      map(resp => { 

       }),
      catchError(err => { 

       })
    );
      
  }
}

In catchError operator the below error is showing.

Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<void | HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse | HttpUserEvent>) => ObservableInput<...>'. Type 'void' is not assignable to type 'ObservableInput'.

19       catchError(err => {
2

2 Answers

1
votes

RxJS catchError operator must return an observable. If you have nothing to return you could forward the supplied error using RxJS throwError function.

import { throwError } from 'rxjs';

return next.handle(req).pipe(
  map(resp => { }),
  catchError(err => { 
    // handle error
    return throwError(err);      // forward the supplied error
  })
);
1
votes

You can gracefully handle the error by return an Observable message like :

import { of } from 'rxjs';

catchError(err => of('Error happened'))

or forward it like :

catchError(err => throwError(err))

In either way you have to return an Observable. You have good exemples here