Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Error Handling Angular 14 - throwError deprecated

Tags:

angular

So in an earlier version of Angular I had a generic CRUD service and this worked fine:

 deleteById<T>(id: any, apiMethod: string): Observable<T> {

    let callPoint = this.endpoint.concat('/', apiMethod, '/', id);

    return this.httpClient.delete<T>(callPoint, this.httpHeader)
      .pipe(
        retry(1),
        catchError(this.processError)
      )
  }

  processError(err: { error: { message: string; }; status: any; message: any; }) {
    let message = '';
    if (err.error instanceof ErrorEvent) {
      message = err.error.message;
    } else {
      message = `Error Code: ${err.status}\nMessage: ${err.message}`;
    }
    console.log(message);
    return throwError(message);
  }

I now recieve a warning against the return throwError(message); line of processError stating that throwError is deprecated.

If I change this line to:

return new Error(message);

I then get errors against my catchError call in my deleteById method. The catchError now does not like that I am passing this.processError.

I've been scouring the internet, but cannot find any good examples of how I might be able to change this.

Any ideas greatly appreciated.

like image 429
bilpor Avatar asked Feb 13 '26 13:02

bilpor


1 Answers

Accordingly with the RxJs documentation the throwError function uses a function as a parameter.

https://rxjs.dev/api/index/function/throwError

So what you should do is the following.

processError(err: any) { 
  let message = '';
  if (err.error instanceof ErrorEvent) {
    message = err.error.message;
  } else {
    message = `Error Code: ${err.status}\nMessage: ${err.message}`;
  }
  console.log(message);
  return throwError(() => new Error(message)); // use throwError from the rxjs package
}

Hope it helps you!

like image 99
Diego Bascans Avatar answered Feb 15 '26 11:02

Diego Bascans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!