简体   繁体   中英

Throw an error "inside" an observable in angular

I want the same behavior as ReplaySubject.next(), but for errors (ReplaySubject.nextError())

Something that will make the error part of the subscription execute

I know about the ThrowError operator, but it doesn't work for me because it is creating a new observable that will throw an error, while I want an existing observable ( ReplaySubject ) to throw an error upon subscription.

obs = ReplaySubject(1);
obs.nextError('some error');
obs.subscribe(res=> {'this should not execute')} err=>{console.log('this should execute')})

You can use .error(someError)

Observers have 3 functions. next , error , and complete

Subjects (and ReplaySubjects) are both observers and observables, as such you can call .error on a subject.

const a$ - new Subject();
a$.subscribe({
  error: err => console.log("This is an error:", err);
});
a$.error("Imperatively emitted error");

Just throw use throwError in a switchMap .

of('some value')
  .pipe(
    switchMap((ms) => {
      return throwError(() => new Error(`Errory McErrorFace`));
    })
  )
  .subscribe({
    next: console.log, // not called
    error: console.error, // called
  });

You can throw, inside of it

import { ReplaySubject, tap } from 'rxjs';

const obs = new ReplaySubject(1);

obs.next('hello');

const obsConsumer = obs.pipe(
  tap(() => {
    throw 'err';
  })
);

obsConsumer.subscribe({
  next: (res) => {
    console.log('this should not execute');
  },
  error: (err) => {
    console.log('this should execute');
  },
});

Stackblitz

( I have corrected a few things, like not using new, using the deprecated method to subscribe )

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