Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finalize() method not throwing unhandled exceptions

Tags:

rxjs

The finalize() method seems to be catching unhandled exceptions and not doing anything with them.

Running the following code in my angular project, the console log will run but nothing after the thrown error (expected). But, there is no evidence of the thrown error, in devtools or anywhere else. Is there any reason for this? I can't see anywhere defining this as intended functionality. And being the last action of a subscription I do not think passing this error to catchError() makes sense.

this.obsService.getSubject().pipe(finalize(() => {
  console.log(1);
  throw new Error('Finalize issue');
  this.performFinalActions();
})).subscribe();

Should this just be logged as an issue with RxJS directly?

EDIT: An error is thrown currectly if getSubject is a RxJS Subject but if another observable such as HttpClient.get the error dissappears from any logs.

like image 472
Starsky Torchia Avatar asked Jul 01 '26 23:07

Starsky Torchia


1 Answers

  1. Throw new error stops execution of code after it happens, so the below code is dead code (performFinalActions).

  2. We need to emit values from the subject for the error to be shown on console.

  3. The finalize happens after the error happens so it's working fine.

  4. The finalize code will happen only after the subject is completed, else it won't be called.

Working example below:

import { Subject } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';

function performFinalActions() {
  console.log('performing actions');
}
const subject$ = new Subject();

subject$
  .pipe(
    finalize(() => {
      console.log(1);
      throw new Error('Finalize issue');
      performFinalActions();
    })
  )
  .subscribe({
    next: (data: any) => console.log('next', data),
    error: (data: any) => console.log('error', data),
    complete: () => {
      console.log('complete');
    },
  });

subject$.next('asdf');
subject$.complete();

Stackblitz Demo

like image 61
Naren Murali Avatar answered Jul 04 '26 18:07

Naren Murali



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!