简体   繁体   中英

catchError operator showing problem in angular interceptor

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 => {

RxJScatchError 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
  })
);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM