简体   繁体   中英

Some trouble with "catchError" angular function

I had an error

this is an error

So I am learning how to catch errors with the catchError function in angular htttp services I have a ts file that executes function handler errors

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable({providedIn: 'root'})export class ProcessHttpMsgService {

constructor() { }

public handelError(error: HttpErrorResponse| any){let errMsg: string;

if (error.error instanceof ErrorEvent) {
  errMsg = error.error.message;
} else {
  errMsg =`${error.status}- ${error.statusText || ''} ${error.error}`
}

return  new Error(errMsg)

}}

And I have a service that uses this function:

import { Injectable } from '@angular/core';
import { Dish } from "../shared/dish";
import {catchError, Observable, scheduled} from 'rxjs'import { map } from "rxjs";import { HttpClient } from "@angular/common/http";
import { baseURL } from "../shared/baseurl";
import {ProcessHttpMsgService} from "./process-http-msg.service";

@Injectable({providedIn: 'root'})
export class DishService {

constructor(private http: HttpClient,
private processHttpMsgService:ProcessHttpMsgService){
}

getDishes(): Observable<Dish[]>{return this.http.get<Dish[]>(baseURL + 'dishes').pipe(catchError(this.processHttpMsgService))}

getDish(id: string): Observable<Dish>{return this.http.get<Dish>(baseURL + 'dishes/' + id)}

getFeaturedDish():Observable<Dish>{return this.http.get<Dish[]>(baseURL +  'dishes?featured=true').pipe(map(dishes => dishes[0]))}

getDishIds(): Observable<number[] | any>{return this.getDishes().pipe(map(dishes => dishes.map(dish => dish.id)))}
}

This is because you are trying to pass an service class to catchError . catchError expects you to pass it a function. That function is then supposed to either throw a new Error , or return an Observable .

Something like:

getDishes(): Observable<Dish[]> {
  return this.http.get<Dish[]>(baseURL + 'dishes').pipe(
    catchError((error => {
      if (error.error instanceof ErrorEvent) {
        errMsg = error.error.message;
      } else {
        errMsg = `${error.status}- ${error.statusText || ''} ${error.error}`
      }

      throw new Error(errMsg)
    })
  );
}

Two small mistakes here:


First, catchError expects a function, not an object. RxJS is used heavily in Angular, but it's not part of angular. It's a standalone library. Important not to confuse the two.

So, if catchError expects a function and you want to call ProcessHttpMsgService.handleError , you can do this:

.pipe(catchError(e => this.processHttpMsgService.handleError(e)));

Secondly the reference ( https://rxjs.dev/api/operators/catchError ) describes catchError as follows (emphasis mine):

Catches errors on the observable to be handled by returning a new observable or throwing an error.

return new Error(errMsg); will return an instance of Error , which is neither of the two options.

You either have to

a) return an Observable , for example throwError :

public handleError(error: HttpErrorResponse | any) {
  ...

  return throwError(() => new Error(errMsg));
}

or b) throw an Error using the throw statement. In that case you also have to tell RxJS that your function will throw and never return. Set the return type explicitly to never :

//                                                 VVVVV
public handleError(error: HttpErrorResponse| any): never {
  ...
}

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