'Handling Error in HTTPClient get method not working

I am trying to catch error in HTTP get message in my service file.

Here is the script:

import { Injectable } from '@angular/core';
import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfolio-epic.model';
import { HttpClient, HttpErrorResponse, HttpParams} from '@angular/common/http'
import { config, Observable } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

refreshPortfolioEpicsList(id:number):Observable<PortfolioEpicModel[]>{   
  this.baseUrl=this.conf.getSettings("apiUrl");
  return this.http.get<PortfolioEpicModel[]>(this.baseUrl+ "/api/pepics/"+ id.toString())
    .pipe(catchError(this.errorHandler));
}

errorHandler(error:HttpErrorResponse){
  console.info(error.message);
}

But the catchError call shows this error:

Argument of type '(error: HttpErrorResponse) => void' is not assignable to parameter of type '(err: any, caught: Observable<PortfolioEpicModel[]>) => ObservableInput'. Type 'void' is not assignable to type 'ObservableInput'.ts(2345)

I didn't understand how to deal with it.

I am working in Angular 11.



Solution 1:[1]

You can use throwError from rxjs.

import { throwError } from 'rxjs';

errorHandler(error: HttpErrorResponse) {
  console.info(error.message);

  return throwError(error.message || "server error.");
}

Sample Solution with Success and Error Demo on StackBlitz

Solution 2:[2]

You're getting that error because the errorHandler function you're passing to the RxJS catchError operator requires either to return an Observable or to re-throw the error (like @Yong Shun has shown in his answer)

You can check the official documentation here for the catchError operator: https://rxjs.dev/api/operators/catchError

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 sp814610