Search code examples
javascriptrxjs

RxJS: The signature '(error: any): Observable<never>' of 'throwError' is deprecated.(6387)


When I try to use throwError from inside the catchError to return an error, I get the following deprecation message

The signature '(error: any): Observable' of 'throwError' is deprecated.(6387)

const { Observable, throwError } = rxjs;
const { catchError } = rxjs.operators;

new Observable((observer) => {
  observer.next('first emission');
  observer.error('error emission');
  observer.complete();
}).pipe(
  catchError((error) => {
    console.log('Caught error:', error);
    return throwError(error);                // <-- deprecation here
  })
).subscribe({
  next: (value) => console.log('Next:', value),
  error: (error) => console.log('Error:', error),
  complete: () => console.log('Complete')
});
.as-console-wrapper { max-height: 100% !important; top: 0px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.4.0/rxjs.umd.min.js"></script>

Deprecation reproduction: Stackblitz


Solution

  • The reason for deprecation is explained here:

    Support for passing an error value will be removed in v8. Instead, pass a factory function to throwError(() => new Error('test')). This is because it will create the error at the moment it should be created and capture a more appropriate stack trace. If for some reason you need to create the error ahead of time, you can still do that: const err = new Error('test'); throwError(() => err);

    So we could either do

    .pipe(
      catchError((error) => {
        return throwError(() => new Error(error));
      })
    ).subscribe({
      error: (error) => console.log('Error:', error.message)
    });
    

    or

    .pipe(
      catchError((error) => {
        return throwError(() => error);
      })
    ).subscribe({
      error: (error) => console.log('Error:', error)
    });
    

    Working example: Stackblitz